动态给实例添加属性和方法
例子:
from types import MethodType #用于动态添加方法,引入MethodType class cat(object): pass #定义一个空类 cat1 = cat() cat1.name = "Tom" #动态添加属性 print(cat1.name) def run(self): #先定义一方法 print(self.name+"在奔跑") cat.run = MethodType(run,cat1) #动态添加方法 cat1.run() #调用方法
限制动态添加属性__slots__
class cat(object): __slots__=("name","age") #限制实例属性,只能添加括号内有的属性
运算符的重载
例子:__add__
class Person(object): def __init__(self,num): self.num = num #运算符重载 def __add__(self, other): return Person(self.num + other.num) def __str__(self): return "num = "+str(self.num) per1 = Person(1) per2 = Person(2) print(per1+per2)
__lt__ :
# operator.lt(a, b) import operator # print(operator.lt(3, 2)) #前面的数小于后边的数 为Ture # print(operator.lt(1, 2)) #前面的数大于后边的数 为False class Grade(object): def __init__(self,num): self.num = num #lt运算符重载 def __lt__(self, other): if self.num > other.num: #冒号一定不同要忘记 return 1 if self.num == other.num: return 0 if self.num < other.num: return 2 # def __str__(self): # return "num = "+str(self.num) # print(pow(2,2)) gra1 = Grade(2) gra2 = Grade(3) print(operator.lt(gra2, gra1)) # print(pow(gra1,2))
__pow__ #平方
class Grade(object): def __init__(self,num): self.num = num #lt运算符重载 平方 def __pow__(self, power, modulo=None): return Grade(pow(self.num,power)) def __str__(self): return "num = "+str(self.num) # print(pow(2,2)) gra1 = Grade(2) #定义一个对象 print(pow(gra1,2)) #验证运算符的重载 pow讲解:
https://blog.csdn.net/weixin_39712705/article/details/112315901
operator --- 标准运算符替代函数: