【问题标题】:python built-in functions vs magic functions and overriding [duplicate]python内置函数与魔术函数和覆盖[重复]
【发布时间】:2012-11-10 18:34:36
【问题描述】:

可能重复:
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)

输出让我感到惊讶:

a.__str__:  custom__getattribute__ - __str__
str(a):  custom__str__
  • str(a)不应该映射到魔法方法吗 a.__str__()?
  • 如果我删除自定义ClassA.__str__(),那么 ClassA.__getattribute__() 仍然没有接听电话。怎么会?

【问题讨论】:

标签: python overriding magic-function


【解决方案1】:

正如 user1579844 所链接的那样,新式类避免了 __getattribute__ 的正常查找机制,并在解释器调用它们时直接加载方法。这样做是出于性能原因,因为这种神奇的方法非常普遍,以至于标准查找会大大降低系统速度。

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

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

【讨论】:

    【解决方案2】:

    当你打电话时

    a.__str__ 
    

    考虑过

    __str__
    

    作为 item 在构造函数中。

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

    在这一行:

    print 'custom__getattribute__ - ' + item  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多