python内置函数vs魔术函数和重写

2024-05-01 21:39:36 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Intercept operator lookup on metaclass
How can I intercept calls to python’s “magic” methods in new style classes?

考虑以下代码:

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)

结果令我吃惊:

^{pr2}$
  • str(a)不应该映射到magic方法吗 a.__str__()?在
  • 如果我删除自定义ClassA.__str__(),那么 ClassA.__getattribute__()仍然没有接到电话。怎么会?在

Tags: selfreturndefmagiccustomlookupitemoperator
2条回答

当你打电话来的时候

a.__str__ 

有人考虑过

^{pr2}$

作为构造函数中的。在

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

在这一行中:

print 'custom__getattribute__ - ' + item  

正如user1579844所链接的那样,新类型的类避免了通常的ugetattribute查找机制,并在解释器调用它们时直接加载方法。这样做是出于性能的原因,因为这是一种非常常见的魔术方法,标准查找会极大地减慢系统的速度。在

当你用点表示法显式地调用它们时,你又回到了标准查找中,所以你首先调用了ugetattribute。在

如果您在Python2.7中工作,则可以使用旧样式的类来避免这种行为,否则请查看建议的线程中的答案以找到解决方案。在

相关问题 更多 >