python3 高级编程(二) 动态给类添加方法功能
发布时间:2020-12-20 10:55:04 所属栏目:Python 来源:网络整理
导读:class Student(object): pass 给实例绑定一个属性: s = Student() s.name = ‘ Michael ‘ # 动态给实例绑定一个属性 print (s.name)Michael 给实例绑定一个方法: def set_age(self,age): # 定义一个函数作为实例方法 ... self.age = age... from types im
class Student(object): pass 给实例绑定一个属性: >>> s = Student() >>> s.name = ‘Michael‘ # 动态给实例绑定一个属性 >>> print(s.name) Michael 给实例绑定一个方法: >>> def set_age(self,age): # 定义一个函数作为实例方法 ... self.age = age ... >>> from types import MethodType >>> s.set_age = MethodType(set_age,s) # 给实例绑定一个方法 >>> s.set_age(25) # 调用实例方法 >>> s.age # 测试结果 25 但是,给一个实例绑定的方法,对另一个实例是不起作用的: >>> s2 = Student() # 创建新的实例 >>> s2.set_age(25) # 尝试调用方法 Traceback (most recent call last): File "<stdin>",line 1,in <module> AttributeError: ‘Student‘ object has no attribute ‘set_age‘ 为了给所有实例都绑定方法,可以给class绑定方法: >>> def set_score(self,score): ... self.score = score ... >>> Student.set_score = set_score 给class绑定方法后,所有实例均可调用: >>> s.set_score(100) >>> s.score 100 >>> s2.set_score(99) >>> s2.score 99 通常情况下,上面的 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |