目录
动态添加类属性与方法
定义时添加:
class Person(object): #创建类
def __init__(self, name): #构造函数
self.name = name
def getName(self): #类中的方法(函数)
return self.name
girl = Person('canglaoshi') #实例化
name = girl.getName() #调用方法(函数)
print("the person's name is: ", name)
动态添加:有些情况没有在定义类是添加它的属性或者方法(比如,我们使用第三方函数库的时候)。但可以通过动态的方法,在程序执行的过程中添加。
1.使用types.MethodType这个方法
import types
class Person(object):
def __init__(self,name):
self.name = name
def run(self):
print('%s在奔跑' % self.name)
p1 = Person('p1')
p1.run = types.MethodType(run,p1)
p1.run()
2.直接将这个函数赋值给类但是需要使用classmethod装饰器将这个方法设置为一个类方法。
import types
class Person(object):
country = 'china'
def __init__(self,name):
self.name = name
def run(cls):
print('%s在奔跑' % cls.country)
Person.run = run
Person.run()
@property
什么是@property:python内置有三大装饰器:@staticmethod(静态方法)、@classmethod(类方法)、@property(描述符),其中静态方法就是定义在类里的函数,并没有非要定义的必要;类方法则是在调用类属性、传递类对象时使用;而@property则是一个非常好用的语法糖。@property最大的好处就是在类中把一个方法变成属性调用,起到既能检查属性,还能用属性的方式来访问该属性的作用。
作用:1.只读属性。2.限制属性。
只读属性:
class Person(object):
def __init__(self, name, age=18):
self.name = name
self.__age = 18
@property
def age(self):
return self.__age
xm = Person('xiaoming') #定义一个人名小明
print(xm.age) #结果为18
xm.age = -4 #报错无法给年龄赋值
print(xm.age)
限制属性:
class Person(object):
def __init__(self, name, age):
self.name = name
self.__age = 18
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if age < 18:
print('年龄必须大于18岁')
return
self.__age = age
return self.__age
xm = Person('xiaoming', 20)
print(xm.age)
print('----------')
xm.age = 10
print(xm.age)
print('----------')
xm.age = 20
print(xm.age)
运算符重载
什么是运算符重载:让自定义的类生成的对象(实例)能够使用运算符进行操作。
作用:1.让自定义类的实例像内建对象一样进行运算符操作。2.让程序简洁易读。3.对自定义对象将运算符赋予新的规则。
算术运算符重载:
方法名 运算符和表达式 说明
__add__(self,other) self + other 加法
__sub__(self,other) self - other 减法
__mul__(self,other) self * other 乘法
__truediv__(self,other) self / other 除法
__floordiv__(self,other) self // other 地板除
__mod__(self,other) self % other 取模(求余)
__pow__(self,other) self **other 幂运算
实例:
class Person:
def __init__(self,num):
self.num = num
def __add__(self, other):
return Person(self.num + other.num)
def __sub__(self, other):
return Person(self.num - other.num)
p1 = Person(12)
p2 = Person(13)
print(p1+p2)
print(p1-p2)
比较算数运算符重载:
方法名 运算符和表达式 说明
__lt__(self, other) self < other 小于
__le__(self, other) self <= other 小于等于
__gt__(self, other) self > other 大于
__ge__(self, other) self >= other 大于等于
__eq__(self, other) self == other 等于
__ne__(self, other) self != other 不等于
实例:
print(operator.lt(score1**score2,score3**score4))