2012-01-12 159 views
2
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 

請注意,重要的是檢索應該發生在類而不是實例。

+0

它在我看來像你沒有掌握這個類的東西是如何工作的。你所做的只是沒有意義。如果你還沒有掌握它,Python手冊和教程是很好的東西。 – 2012-01-12 10:30:13

+0

這是一種有趣的...我不知道爲什麼'test2.newfunc()'工作... – DonCallisto 2012-01-12 12:06:13

+0

@羅曼的答案是完全正確的。當你做test2.newfunc = Test.Func時,你被「繞過」對象定義,並直接進入函數定義。所以,不需要參數。現在很清楚 – DonCallisto 2012-01-12 12:11:27

回答

2

調查的位:

>>> test1.func 
<bound method Test.func of <__main__.Test instance at 0x800f211b8>> 
>>> Test.func 
<unbound method Test.func> 

然後用戶自定義綁定的方法(test1.func在我們的例子)被調用,這個調用實際上是這樣,他們通常有一個self參數聲明作爲Test.func(test1)執行 - 類實例始終作爲第一個參數傳遞。

Python Data model查看更多關於此主題的信息。上述


編輯

輸出從Python 2.6中。由於Test.func()爲你工作,我假設你使用Python 3。在這種情況下,輸出會成爲下一個:

>>> test1.func 
<bound method Test.func of <__main__.Test object at 0xb747624c>> 
>>> Test.func 
<function func at 0xb74719ec> 

正如你看到的,Test.func是一個簡單的功能,所以沒有「魔法」將增加,而稱它。

+0

是的。但是我仍然不明白什麼時候調用test2.newfunc(),爲什麼test2不會作爲參數傳遞。謝謝。 – dragonfly 2012-01-12 09:51:39

+0

@dragonfly見編輯。 – 2012-01-12 10:20:23

+0

感謝您的幫助。我想我明白了。 – dragonfly 2012-01-12 12:18:11

6

在類的實例上調用的類的方法將自動傳遞實例引用作爲參數。

class Test: 
     def func(self): 
      print('func') 

test1 = Test() 
test1.func() # self = test1 
+0

謝謝。我不擅長英語。我想我知道你的意思。當調用test1.func()時,將傳遞實例引用test1。但是,當調用test2.newfunc()時,爲什麼實例引用test2未傳遞。你知道同樣的方法 - func()被調用。 – dragonfly 2012-01-12 09:45:29