覆盖的方法不包含自我?(Overwritten Methods don't contain self?)
这是我刚刚在我的机器上播放的一个例子:
$ 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? 我需要做些什么来获得对自我的引用?
Here is an example I just played through on my machine:
$ 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() helloWhat is happening here? Why doesn't the function get the parameter self, when it is used as a method? What would I need to do, to get a reference to self inside it?
最满意答案
通过实例引用的类中的方法绑定到该实例,在您的情况下:
In [3]: a.hi Out[3]: <bound method A.hi of <__main__.A object at 0x218ab10>>相比于:
In [4]: A.hi Out[4]: <unbound method A.hi>所以,要达到你可能想要的效果,请这样做
In [5]: def hello(self): ...: print "hello" ...: In [6]: A.hi = hello In [7]: a.hi() hello注意 - 这将适用于A所有实例。 但是,如果你只想在一个实例上覆盖一个方法,你是否真的需要通过self ?
A method in a class referenced via an instance is bound to that instance, in your case:
In [3]: a.hi Out[3]: <bound method A.hi of <__main__.A object at 0x218ab10>>Compare to:
In [4]: A.hi Out[4]: <unbound method A.hi>So, to achieve the effect you probably want, do
In [5]: def hello(self): ...: print "hello" ...: In [6]: A.hi = hello In [7]: a.hi() helloBeware - this will apply to all instances of A. But if you want to override a method on one instance only, do you really need to pass self?
更多推荐
发布评论