Python 内置函数与魔术函数和覆盖



可能的重复项:
元类
上的截获运算符查找 如何在新样式类中拦截对 python "魔术"方法的调用?

请考虑以下代码:

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)不应该映射到魔术方法吗 a.__str__()
  • 如果我删除自定义ClassA.__str__(),则 ClassA.__getattribute__()仍然没有接到电话。怎么来了?

正如user1579844所链接的那样,正在发生的事情是新样式类避免了__getattribute__的正常查找机制,并在解释器调用它们时直接加载方法。这样做是出于性能原因,这是一种非常常见的神奇方法,以至于标准查找会严重减慢系统速度。

当您使用点表示法显式调用它们时,您将回退到标准查找,因此您首先调用__getattribute__。

如果您使用的是python 2.7,则可以使用旧样式类来避免此行为,否则请查看建议的线程中的答案以找到一些解决方案。

当你调用时

a.__str__ 

它被认为是

__str__

作为构造函数中的

def __getattribute__(self, item):
        print 'custom__getattribute__ - ' + item
        return ''

在这一行中:

print 'custom__getattribute__ - ' + item  

最新更新