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__()
仍然没有接到电话。怎么会?在
当你打电话来的时候
有人考虑过
^{pr2}$作为构造函数中的项。在
在这一行中:
正如user1579844所链接的那样,新类型的类避免了通常的ugetattribute查找机制,并在解释器调用它们时直接加载方法。这样做是出于性能的原因,因为这是一种非常常见的魔术方法,标准查找会极大地减慢系统的速度。在
当你用点表示法显式地调用它们时,你又回到了标准查找中,所以你首先调用了ugetattribute。在
如果您在Python2.7中工作,则可以使用旧样式的类来避免这种行为,否则请查看建议的线程中的答案以找到解决方案。在
相关问题 更多 >
编程相关推荐