這裏我只是通過發揮我的機器上的例子:覆蓋的方法不包含自我?
$ python
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
# just a test class
>>> class A(object):
... def hi(self):
... print("hi")
...
>>> a = A()
>>> a.hi()
hi
>>> def hello(self):
... print("hello")
...
>>>
>>> hello(None)
hello
>>>
>>>
>>>
>>> a.hi = hello
# now I would expect for hi to work the same way as before
# and it just prints hello instead of hi.
>>> a.hi()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: hello() takes exactly 1 argument (0 given)
>>>
>>> def hello():
... print("hello")
...
# but instead this one works, which doesn't contain any
# reference to self
>>> a.hi = hello
>>> a.hi()
hello
>>>
>>>
>>>
>>>
>>> a.hello = hello
>>> a.hello()
hello
這到底是怎麼回事?當它用作方法時,爲什麼函數不會獲得參數self?我需要做些什麼來獲得對自我的引用?
一個很好的例子,「我已經知道,但不知何故不適用於當前的情況」。感謝您清理它。 – erikbwork