动态给实例添加属性和方法并使用
- 给人动态添加说话的方法
from types import MethodType
class Person(object):
pass #创建一个空类
per=Person()
#动态添加属性
per.name="tom"
print(per.name)
#动态添加方法
def say(self):
print("my name is "+self.name)
per.speak=MethodType(say,per)
per.speak()
输出
tom
my name is tom
- 动态给类添加方法,具体是对猫的类中没有设置奔跑的方法,在类外添加这个方法,并打印显示
from types import MethodType #导入MethodType方法
class cat(object): #定义猫类
def eat(self): #定义吃的方法
print("猫会吃") #输出
#动态添加方法
def run(self): #定义跑的方法
print("猫会跑") #输出
cat1=cat() #实例化一个猫对象
cat1.run = MethodType(run,cat)
cat1.run() #调用猫会跑方法
输出
猫会跑
运算符重载
对__pow__、__lt__进行运算符重载,主要对的两个成绩进行平方运算、比较两个成绩
class student:
# 构造方法,给属性赋值
def __init__(self, course1, course2): # 定义构造方法
self.course1 = course1 # 定义学生分数1属性
self.course2 = course2 # 定义学生分数2属性
# 重写pow方法
def __pow__(self, power, modulo=None):
return pow(self.course1, power) #返回分数的平方
# 重写cmp方法
def __lt__(self):
if self.course1 > self.course2: #如果course1 > course2
return str(self.course1)+">"+str(self.course2)
elif self.course1 < self.course2:#如果course1 < course2
return str(self.course1)+"<"+str(self.course2)
else:
return "equal"
# 实例化student对象
student1 = student(80, 85)
# 调用重写的pow方法
print(pow(student1, 2))
# 调用重写的cmp方法
print(student1.__lt__())
输出
6400
80<85