python内置函数与魔术函数和覆盖 [英] python built-in functions vs magic functions and overriding

查看:103
本文介绍了python内置函数与魔术函数和覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
对元类的拦截运算符查找
如何截获对新样式类中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)

输出令我惊讶:

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 method a.__str__()?
    • If I remove the custom ClassA.__str__(), then ClassA.__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内置函数与魔术函数和覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆