Python:描述符如何伪装对象的属性,它是如何工作的?

Python: how does descriptors disguise object`s attributes and how does it work?

大家好!我有一个问题:我不完全理解描述符“设置”a attribute.I 是如何在代码中写下我的猜测的,如果它们不正确,你能告诉我正确的变体吗?提前致谢!

class Descriptor:
    _counter = 0

    def __init__(self):
        self.attr_name = f'Descriptor attr#{Descriptor._counter}'
        Descriptor._counter += 1

    def __get__(self, instance, owner):
        return self if instance is None else instance.__dict__[self.attr_name]

    def __set__(self, instance, value):
        if value > 0:
            instance.__dict__[self.attr_name] = value
        else:
            msg = 'Value must be > 0!'
            raise AttributeError(msg)

class Shop():
    weight = Descriptor()
    price = Descriptor()


    def __init__(self, name, price, weight):
        self.name = name
        self.price = price  # Descriptor.__set__(price, self, price)
        self.weight = weight  # Descriptor.__set__(weight, self, weight)
        # Is it correct?

    def __repr__(self):
        return f'{self.name}: price - {self.price} weight - {self.weight}'

    def buy(self):
        return self.price * self.weight

基本上是的,虽然你的猜测 Descriptor.__set__(price, self, price) 提到了 price 两次所以我猜你的意思。准确地说,它运行这个:

Descriptor.__set__(type(self).__dict__["price"], self, price)