Python是动态语言,它可以在写好了一个类之后再给类动态地添加属性和方法
对于类生成出的实例同样可以这样做
要实现这一功能需要借助一个方法:MethodType
用法:
<类(或者实例)>.<为要添加的方法或属性起的名字> = MethodType(<要添加的方法或属性>, 类(或者实例))
举例:
可以先这样导入这个方法 from types import MethodType
假设我们定义一个 Student
类:
class Student(object):
pass
现在里面什么也不写,我们在外面给它动态增加方法
考虑这样一个函数:
def set_score(self, score: int):
self.score = score
只需写入这样一行代码即可把set_score()
方法添加为 Student
类的 .set_score()
方法:
Student.set_score = MethodType(set_score, Student)
之后就可以这样使用这个方法了:
Student.set_score(99)
绑定属性以及对类实例绑定的做法类似
下面是一个DEMO:
# 类的高级用法1
from types import MethodType
class Student(object):
pass
def main():
s = Student()
s.name = 'Bob'
print(s.name)
def set_age(self, age: int): # 给实例定义的方法
self.age = age
s.set_age = MethodType(set_age, s) # 将方法与一个实例绑定, 这样实例s就有了set_age()方法
s.set_age(5) # 这样一来实例s有了一个属性: s = 5
print(s.age)
# 当然也可以给类绑定方法
def set_score(self, score: int):
self.score = score
Student.set_score = MethodType(set_score, Student)
Student.set_score(99)
print(Student.score)
# 这样Student类就有了set_score()方法和score属性,该类所有实例都可用,如下:
s.set_score(80)
print(s.score) # 会输出80而不是99
if __name__ == '__main__':
main()
运行结果:
Bob
5
99
80