"class" vs "instance of class" __get__ 和 __set__?

"class" vs "instance of class" __get__ and __set__?

问:为什么 hh.a = 2 不是我期望的,但 b.a = 2 可以?

代码如下:

class D:
    def __init__(self):
        print('this is init')
        self.name = ''

    def __get__(self,instance,owner):
        print('getting')
        return self.name


    def __set__(self,instance,value):
        print('setting')
        self.name = value
        return self.name

和...

class hh:
    a = D()

b = hh()

当我设置 hh.a = 2 时,它不会调用 print('setting') 但 b.a = 2 可以。你能解释一下吗?

描述符设置器仅在对拥有描述符的 class 的实例设置属性时激活。它们不适用于 class 本身或其子 class。这记录在 Python data model.

3.3.2.1. Implementing Descriptors

...

object.__set__(self, instance, value)

Called to set the attribute on an instance instance of the owner class to a new value, value.