为什么__getattr__能够处理python 2.x中的内置运算符重载? [英] Why is __getattr__ capable of handling built-in operator overloads in python 2.x?

查看:57
本文介绍了为什么__getattr__能够处理python 2.x中的内置运算符重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 2.x中采用以下类:

In python 2.x take the following class:

class Person:
    def __init__(self, name):
        self.name = name

    def myrepr(self):
        return str(self.name)

    def __getattr__(self, attr):
        print('Fetching attr: %s' % attr)
        if attr=='__repr__':
            return self.myrepr

现在,如果您创建实例并在外壳中回显它(调用 __ repr __ ),例如

Now if you create an instance and echo it in the shell (to call __repr__), like

 p = Person('Bob')
 p

您得到

Fetching attr: __repr__
Bob

没有 __ getattr __ 重载,有了默认的< __ main__。实例位于0x7fb8800c6e18> 之类的东西。

Without the __getattr__ overload you'd have just got the default <__main__.A instance at 0x7fb8800c6e18> kind of thing.

我的问题是为什么内置的 __ getattr __ 甚至能够处理对 __ repr __ 的调用(以及其他内置这样)(如果未在其他地方定义)。这些不是属性,它们是运算符,更像方法。。

My question is why is the built-in __getattr__ even capable of handling calls to __repr__ (and other builtins like that) if they are not elsewhere defined. These are not attributes they are operators, more like methods..

(这在python 3.x中不再起作用,所以我想他们摆脱了__getattr__的处理内置函数。)

(This no longer works in python 3.x so I guess they got rid of the handling by __getattr__ of the builtins.)

推荐答案

这不是Python 2或3的东西,而是新式与旧式类。在旧式类中,这些方法没有特殊含义,将它们视为简单属性。

It's not a Python 2 or 3 thing, it's a new-style vs old-style class thing. In old-style classes these methods had no special meaning, they were treated like simple attributes.

在新式类中,特殊方法始终在类(隐式查找)而非实例中查找。


对于新型类,特殊方法的隐式调用只有在
上定义时才能保证正常工作对象的类型,而不是对象实例字典中的

For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

旧类:


对于旧类,特殊方法总是以完全与其他任何方法或属性相同的方式在
中查找。无论是在
x .__ getitem __(i)中显式查找方法还是在<$ c中隐式查找方法,
都是这种情况$ c> x [i] 。

For old-style classes, special methods are always looked up in exactly the same way as any other method or attribute. This is the case regardless of whether the method is being looked up explicitly as in x.__getitem__(i) or implicitly as in x[i].

相关:在实例上覆盖特殊方法

这篇关于为什么__getattr__能够处理python 2.x中的内置运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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