Python-覆盖实例上的特殊方法
发布于 2021-02-02 23:20:23
我希望有人能够回答这个对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>'
>>>
注意repr(a
)如何不会产生“ A”
的预期结果?我想知道为什么会这样,是否有办法实现这一目标…
相比之下,下面的示例仍然有效(也许是因为我们不打算重写特殊方法吗?):
>>> class A(object):
... def foo(self):
... return "foo"
...
>>> def bar(self):
... return "bar"
...
>>> from types import MethodType
>>> a = A()
>>> a.foo()
'foo'
>>> setattr(a, "foo", MethodType(bar, a, a.__class__))
>>> a.foo()
'bar'
>>>
关注者
0
被浏览
126
1 个回答