MethodType绑定到类和把方法直接写到类里有什么不同?
python吧
全部回复
仅看楼主
level 2
灬Maxwell 楼主
一、使用MethodType给类绑定一个方法
class Stu(object):
pass
def set_age(self,age):
self.age=age
from types import MethodType
Stu.set_age=MethodType(set_age,Stu)
A=Stu()
B=Stu()
A.set_age(10)
B.set_age(15)
print(A.age,B.age)#结果都是15
上面的例子为什么都是15,解释说实例A和实例B都没有age属性,原本的就是A.set_age就是给Stu类绑定属性age,给Stu绑定类属性为什么不是Stu.set_age(15)这样的方式?而是以实例A.set_age开头?
二、在类内部定义一个方法
class Student(object):
def set_age(self,age):
self.age=age
A=Student()
B=Student()
A.set_age(10)
B.set_age(15)
print(A.age,B.age)#结果是10和15
MethodType是将方法绑定到实例或者类,教程里也说过绑定类一般都会把方法写进去,原话是这样的:“给class绑定方法后,所有实例均可调用,通常情况下,上面的方法可以直接定义在class中”
这句话我理解的就是MethodType就相当于把方法直接写进class中,为什么会出现上面两种结果,求解释。
MethodType绑定的方法和类内部定义的方法有什么区别?
2016年04月09日 17点04分 1
level 11
set_age 是全局的, A或者B调用都是同一个方法,可以看id() 判断出是同一个对象。
还是看代码吧
2016年04月10日 00点04分 2
level 1
同问
2017年06月24日 14点06分 3
1