class Test:
def func():
print('func')
test1 = Test()
test2 = Test()
test1.func() #TypeError: fun1() takes no arguments (1 given)
test2.newfunc = Test.func
test2.newfunc()#It goes well
# update part
def foo(self):
pass
Test.foo = foo
test1.foo # it is bound method
test2.foo = foo
test2.foo # it is function
# end 这两种方式有什么区别吗?谢谢。
# update part
def foo(self):
pass
Test.foo = foo
test1.foo # it is bound method
test2.foo = foo
test2.foo # it is function
# end 注意,重要的是检索应该在类中进行,而不是在实例中。
发布于 2012-01-12 17:46:44
稍微调查一下:
>>> test1.func
<bound method Test.func of <__main__.Test instance at 0x800f211b8>>
>>> Test.func
<unbound method Test.func>然后调用用户定义的绑定方法(在我们的例子中是test1.func),这个调用实际上是作为Test.func(test1)类的实例作为第一个参数传递的。
有关此主题的更多信息,请参阅Python Data model。
编辑
上面的输出来自Python 2.6。由于Test.func()适用于您,因此我假设您使用的是Python3。在这种情况下,输出将是下一个:
>>> test1.func
<bound method Test.func of <__main__.Test object at 0xb747624c>>
>>> Test.func
<function func at 0xb74719ec>正如您所看到的,Test.func是一个简单的函数,因此在调用它时不会添加“魔法”。
发布于 2012-01-12 16:47:18
在类的实例上调用的类的方法会自动将实例引用作为参数传递。因此,它们通常使用self参数声明:
class Test:
def func(self):
print('func')
test1 = Test()
test1.func() # self = test1https://stackoverflow.com/questions/8832185
复制相似问题