我希望有人可以回答这个对Python有深刻理解的:)
请考虑以下代码:
>>> class A(object):
... pass
...
>>> def __repr__(self):
... return "A"
...
>>> from types import MethodType
>>> a = A()
>>> a
<__main__.A object at 0x00AC6990>
>>> repr(a)
'<__main__.A object at 0x00AC6990>'
>>> setattr(a, "__repr__", MethodType(__repr__, a, a.__class__))
>>> a
<__main__.A object at 0x00AC6990>
>>> repr(a)
'<__main__.A object at 0x00AC6990>'
>>>
Run Code Online (Sandbox Code Playgroud)
注意repr(a)如何不产生"A"的预期结果?我想知道为什么会这样,如果有办法实现这个目标......
我对比一下,下面的例子可行(也许是因为我们没有尝试覆盖特殊方法?):
>>> class A(object):
... def foo(self):
... return "foo"
...
>>> def bar(self):
... return "bar"
...
>>> from types import …Run Code Online (Sandbox Code Playgroud)