为什么用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’。为什么?

讨论数量: 3
pardon110

__init__ 作为python中类似构造方法的存在,它的方法名是双划线而非单线
types.MethodType 用来动态绑定自定义的实例类型方法,它参数是函数与实例对象。

import types

class A:
    def __init__(self, y):
        self.y = y

def func(self):
    print ("执行添加的方法", self.y)

a = A("你")
A.func = types.MethodType(func,a)
a.func()
3年前 评论

def _init_(self, y): 这个方法名错了,应该是__init__

class A:
    def __init__(self, y):
        self.y = y
    def func(self):
        print("执行添加的方法", self.y)
3年前 评论
Jason990420 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!