给类,实例绑定属性和方法

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 
给类绑定方法:

>>> def set_score(self, score): ... self.score = score ... >>> Student.set_score = set_score
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99) >>> s2.score 99 
 

猜你喜欢

转载自www.cnblogs.com/LewisAAA/p/9287059.html