覆盖实例上的特殊方法 [英] Overriding special methods on an instance

查看:53
本文介绍了覆盖实例上的特殊方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能回答这个对Python有深刻理解的问题:)

I hope someone can answer this that has a good deep understanding of 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"的预期结果? 我想知道为什么会这样,是否有办法实现这一目标...

Notice how repr(a) does not yield the expected result of "A" ? I want to know why this is the case and if there is a way to achieve this...

相反,下面的示例可以工作(也许是因为我们不打算重写特殊方法?):

I contrast, the following example works however (Maybe because we're not trying to override a special method?):

>>> 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'
>>>

推荐答案

Python不会调用特殊方法,这些方法的名称在实例上由__包围,而仅在类上,显然可以提高性能.因此,无法直接在实例上覆盖__repr__()并使之正常工作.相反,您需要执行以下操作:

Python doesn't call the special methods, those with name surrounded by __ on the instance, but only on the class, apparently to improve performance. So there's no way to override __repr__() directly on an instance and make it work. Instead, you need to do something like so:

class A(object):
    def __repr__(self):
        return self._repr()
    def _repr(self):
        return object.__repr__(self)

现在,您可以通过替换_repr()来覆盖实例上的__repr__().

Now you can override __repr__() on an instance by substituting _repr().

这篇关于覆盖实例上的特殊方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆