gpt4 book ai didi

python - 如何使用 __getattr__ 将方法委托(delegate)给属性?

转载 作者:行者123 更新时间:2023-11-28 22:35:18 24 4
gpt4 key购买 nike

我有以下类(class):

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__ 吗?

最佳答案

__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

如果您想查看确切的查找过程,它是Objects/typeobject.c 中的_PyObject_LookupSpecial .

如果您想知道为什么 Python 会这样做,那么有很多神奇的方法很难或不可能完成您期望的事情。例如,Python 不可能使用 __getattribute__ 来查找 __getattribute__,因为这会导致没有基本情况的无限递归。

关于python - 如何使用 __getattr__ 将方法委托(delegate)给属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38294904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com