问题描述
我有以下课程:
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)
吗?当在MyInt
类中找不到这样的方法时,不应该调用__getattr__
吗?
Shouldn't i.__add__(1)
be called? And shouldn't __getattr__
be called when no such method is found in the MyInt
class?
推荐答案
__getattr__
不能用于生成其他魔术方法.您需要单独实现所有这些功能.
__getattr__
cannot be used to generate other magic methods. You'll need to implement all of them individually.
当Python语言内部人员查询诸如__add__
之类的魔术方法时,它们会完全绕过__getattr__
,__getattribute__
和实例字典.查找大致像
When the Python language internals look up magic methods like __add__
, they completely bypass __getattr__
, __getattribute__
, and the instance dict. The lookup goes roughly like
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 nofollow> Objects/typeobject.c
.
If you want to see the exact lookup procedure, it's _PyObject_LookupSpecial
in Objects/typeobject.c
.
如果您想知道Python为什么要这样做,那么有很多魔术方法很难做到或根本无法完成您所期望的事情.例如,Python可能无法使用__getattribute__
查找__getattribute__
,因为这将导致无基数的无限递归.
If you're wondering why Python does this, there are a lot of magic methods for which it would be really awkward or impossible to do what you were expecting. For example, Python couldn't possibly use __getattribute__
to look up __getattribute__
, as that would cause infinite recursion with no base case.
这篇关于如何使用__getattr__委托方法进行属性分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!