gpt4 book ai didi

python - 为什么在使用 obj.x 语法调用时不调用 Python 描述符方法?

转载 作者:太空狗 更新时间:2023-10-30 01:21:55 25 4
gpt4 key购买 nike

我这里有一个描述符类X。我尝试在另一个类 Y

中使用描述符 X
class X:
def __init__(self, value):
self.value = value

def __get__(self, instance, owner):
print('#### X.__get__ ####')
return self.value

def __set__(self, instance, value):
print('#### X.__set__ ####')
self.value = value

class Y:
def __init__(self):
self.x = X(10)

y = Y()
print(y.x)
y.x = 20

我希望语句 print(y.x) 会调用 x.__get__ 而语句 y.x = 20 会调用 x.__set__,但它并没有发生。当我运行上面的程序时,我得到了这个输出。

<__main__.X object at 0x7fc65f947950>

为什么没有调用描述符方法?

最佳答案

要调用描述符协议(protocol)方法,您需要将描述符实例(在您的情况下为 X())放在 Y ,不在实例上。这在 Descriptor HowTo Guide 中有一些详细描述。雷蒙德·海廷格:

For objects, the machinery is in object.__getattribute__() which transforms b.x into type(b).__dict__['x'].__get__(b, type(b)).

请注意 b.x 是如何转换为对通过 type(b) 的字典访问获得的描述符的调用。 Y 类应该如下所示:

class Y:
x = X(10)

但是,由于 X 的单个实例将由 Y 的所有实例共享,因此需要修改 X 描述符类从 instance 而不是 self 获取和设置值。

关于python - 为什么在使用 obj.x 语法调用时不调用 Python 描述符方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156182/

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