绑定方法和属性

class Student(object):
    pass

空类

s = Student()
s.name = 'Michael' # 动态给实例绑定一个属性
print s.name

Michael

创建实例,绑定name属性

def set_age(self, age): # 定义一个函数作为实例方法
    self.age = age

from types import MethodType
    s.set_age = MethodType(set_age, s, Student) # 给实例绑定一个方法
    s.set_age(25) # 调用实例方法
    s.age # 测试结果

绑定前,先定义方法 set_age

引入 MethodType

给实例s绑定set_age方法

调用方法

看结果

当然,再创建个新实例,是没有这个绑定关系的。

想给所有实例一次绑定,就给类绑定方法。

原文地址:https://www.cnblogs.com/cutepython/p/6007305.html