问题描述
考虑以下代码:
class ClassA(object):
def __getattribute__(self, item):
print 'custom__getattribute__ - ' + item
return ''
def __str__(self):
print 'custom__str__'
return ''
a=ClassA()
print 'a.__str__: ',
a.__str__
print 'str(a): ',
str(a)
输出令我惊讶:
a.__str__: custom__getattribute__ - __str__
str(a): custom__str__
- 不是
str(a)
应该映射到magic方法a.__str__()
? - 如果我删除自定义
ClassA.__str__()
,则ClassA.__getattribute__()
仍然无法接听电话.怎么会来? - Isn't
str(a)
supposed to be mapped to the magic methoda.__str__()
? - If I remove the custom
ClassA.__str__()
, thenClassA.__getattribute__()
still doesn't catch the call. How come?
推荐答案
如user1579844所链接,正在发生的事情是,新类避免了__getattribute__的常规查找机制,并在解释器调用它们时直接加载该方法.这样做是出于性能方面的考虑,它是一种神奇的方法,非常普遍,以至于标准查找会严重降低系统速度.
As linked by user1579844 what is happening is that the new-style classes avoid the normal lookup mechanism of __getattribute__ and load directly the method when the interpreter call them. This is done for performance reasons, being the magic method so common that the standard lookup would slow down terribly the system.
当您用点符号显式调用它们时,您将退回到标准查找,因此您首先调用__getattribute __.
When you explicitly call them with the dot notation you are falling back to the standard lookup and so you call the __getattribute__ first.
如果您使用的是python 2.7,则可以使用旧样式类避免这种现象,否则请查看建议的线程中的答案以找到一些解决方案.
If you are working in python 2.7 you can avoid this behavior using old style classes, otherwise look to the answers in the thread suggested to find some solution.
这篇关于python内置函数与魔术函数和覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!