Discuss / Python / 想问下通过MethodType给实例绑定方法和我直接给实例绑定方法有什么不同

想问下通过MethodType给实例绑定方法和我直接给实例绑定方法有什么不同

Topic source

SCUT有只Joy

#1 Created at ... [Delete] [Delete and Lock User]

比如说

class A():
    pass

form types import MethodType

a=A()

def test(self):
    print('testing')

a.testfunc1=MethodType(test,a)

a.testfunc2=test

以上这两种有什么区别吗?

SCUT有只Joy

#2 Created at ... [Delete] [Delete and Lock User]

噢 打这段代码后自己试了试发现的确不同的

不好意思没测试过就发上来了。。。

简单的说 如果是用a.testfunc1=MethodType(test,a) 此时test函数需要self参数 如果是用a.testfunc2=test 此时test函数并不需要self参数,否则报错

那其实注意到这点后,这两者的另外的区别又在哪里呢?

我理解的是,a.testfunc1是Class A的实例,而a.testfunc2是个函数,所以不用self参数。


  • 1

Reply