Method 绑定方法到类

来源:互联网 发布:淘宝男士小脚裤 编辑:程序博客网 时间:2024/06/06 01:53
from types import MethodTypeMethodType(函数方法,实例,实例所属类)

实例
1.给实例绑定方法

class Student(object):    passs=Student()from types import MethodTypes.set_age=MethodType(set_age,s,Student)`注意参数设置`s.set_age(25)s.age>>>25

2.给类绑定方法

class Student(object):    passfrom types import MethodTypeStudent.set_age=MethodType(set_age,None,Student)`也可写作:Student.set_age=MethodType(set_age,Student)`s1=Student()s1.set_age(23)s1.age >>>23s2=Student()s2.set_age(25)s2.age>>>25 
原创粉丝点击