为什么用MethodType函数添加方法反而无效
在解释器里输入如下代码:
import types
class A:
def _init_(self, y):
self.y = y
def func(self):
print (‘执行添加的方法’, self.y)
A.func = types.MethodType(func, A)
a = A (‘爱你’)
a.func()
运行结果却是:AttributeError: type object ‘A’ has no attribute ‘y’。为什么?
代码高亮
__init__
作为 python 中类似构造方法的存在,它的方法名是双划线而非单线types.MethodType
用来动态绑定自定义的实例类型方法,它参数是函数与实例对象。def _init_(self, y): 这个方法名错了,应该是__init__