我有以下课程:
class MyInt:
def __init__(self, v):
if type(v) != int:
raise ValueError('value must be an int')
self.v = v
def __getattr__(self, attr):
return getattr(self.v, attr)
i = MyInt(0)
print(i + 1)
我收到错误:TypeError: unsupported operand type(s) for +: 'MyInt' and 'int'
不应该i.__add__(1)
叫做?并且不应该__getattr__
当没有找到这样的方法时被调用MyInt
class?
__getattr__
不能用来生成其他魔法方法。您需要单独实现所有这些。
当Python语言内部查找像这样的魔术方法时__add__
,他们完全绕过__getattr__
, __getattribute__
,以及实例字典。查找过程大致如下
def find_magic_method(object, method_name):
for klass in type(object).__mro__:
if method_name in klass.__dict__:
return klass.__dict__[method_name]
raise AttributeError
如果你想查看确切的查找过程,那就是_PyObject_LookupSpecial
in Objects/typeobject.c https://hg.python.org/cpython/file/2.7/Objects/typeobject.c#l1244.
如果您想知道为什么 Python 会这样做,那么有很多神奇的方法,对于它们来说,执行您所期望的操作会非常尴尬或不可能。例如,Python 不可能使用__getattribute__
去查查看__getattribute__
,因为这会导致没有基本情况的无限递归。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)