【问题标题】:Why isn't the property attribute being replaced by the right hand side when making assignments?为什么在进行分配时属性属性没有被右侧替换?
【发布时间】:2020-07-15 17:16:56
【问题描述】:

给定以下课程(来自https://www.programiz.com/python-programming/property):

# using property class
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    # getter
    def get_temperature(self):
        print("Getting value...")
        return self._temperature

    # setter
    def set_temperature(self, value):
        print("Setting value...")
        if value < -273.15:
            raise ValueError("Temperature below -273.15 is not possible")
        self._temperature = value

    # creating a property object
    temperature = property(get_temperature, set_temperature)

当我们进行赋值c.temperature = 100cCelsius 的一个实例)时,有谁知道它为什么调用setter 函数,而不是将property 对象(即原来的c.temperature)替换为一个号码100

【问题讨论】:

标签: python python-decorators


【解决方案1】:

这就是描述符协议的工作方式。 c.temperature = 100 的含义取决于Celsius.temperature 是否存在。如果是这样,并且定义了 Celsius.temperature.__set__,则使用 Celsius.temperature.__set__(c, 100) 而不是直接为实例属性赋值(例如,c.__dict__['temperature'] = 100)。

property 是一种实现描述符协议的类型。它的__set__ 方法调用setter(在您的示例中为set_temperature)。

【讨论】:

  • 更准确地说,当分配c.temperature 时,仅检查Celsius.temperature__set__ 方法。它在获取实例属性之前检查类(将描述符分配给实例的属性在使用时不会调用它;它仅在类上定义时才有效)。此外,setattr(c, 'temperature', 100) 仍将调用描述符协议,因此它与您描述的没有什么不同(您需要更荒谬的东西,例如 vars(c)['temperature'] = 100 来绕过它)。
  • 谢谢。我认为这些更改现在使答案更加准确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 2021-12-03
  • 2018-12-15
相关资源
最近更新 更多