这是我在机器上玩过的一个示例:$ pythonPython 2.7.4 (default, Apr 19 2013, 18:28:01) [GCC 4.7.3] on linux2Type "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?我需要做什么,才能在其中获得自我的参考?
2 回答
白板的微信
TA贡献1883条经验 获得超3个赞
在您的情况下,通过实例引用的类中的方法绑定到该实例:
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吗?
添加回答
举报
0/150
提交
取消