Python getter和setter的属性装饰器

Python getter和setter的属性装饰器,python,properties,decorator,python-decorators,Python,Properties,Decorator,Python Decorators,对于如何在这个属性代码中获取和设置温度,我有点困惑。这是使用属性装饰器的正确方法吗?但是我不知道如何使用它。我可以调用c.temperature,它返回初始值(0或我用来实例化类的任何值),但之后我无法使用set_temperature()设置温度。我看了几个关于这个话题的答案,但可能没有抓住要点 class Celsius: def __init__(self, temperature=0): self._temperature = temperature def to_f(

对于如何在这个属性代码中获取和设置温度,我有点困惑。这是使用属性装饰器的正确方法吗?但是我不知道如何使用它。我可以调用c.temperature,它返回初始值(0或我用来实例化类的任何值),但之后我无法使用set_temperature()设置温度。我看了几个关于这个话题的答案,但可能没有抓住要点

class Celsius:
  def __init__(self, temperature=0):
    self._temperature = temperature

  def to_f(self):
    return self._temperature * 1.8 + 32

  @property
  def temperature(self):
    print "Celsius:get_temperature"
    return self._temperature

  @temperature.setter
  def temperature(self, value):
    if value < -273:
        raise ValueError("Temperature below -273 is impossible")
    print "Celsius:set_temperature"
    self._temperature = value
class摄氏度:
def _初始(自身,温度=0):
自身温度=温度
def至_f(自身):
返回自身温度*1.8+32
@财产
def温度(自身):
打印“摄氏度:获取温度”
返回自身温度
@温度调节器
def温度(自身、数值):
如果值<-273:
提升值错误(“温度不可能低于-273”)
打印“摄氏度:设置温度”
自身温度=数值

属性允许您连接到属性访问,并设置属性。当您指定属性时,将调用setter:

c = Celsius(20)
c.temperature = 40
但是请注意,在Python 2中,您需要从
对象
继承属性才能工作:

class Celsius(object):
演示:


“但在此之后,我无法使用set_temperature()设置温度”-为什么您希望会出现名为
set_temperature
?你从来没有用这个名字定义过任何东西。事实上,即使只使用c.temperature=10,它也不起作用。例如,我想,因为我没有从对象继承(如下面另一个答案中所述)。谢谢,是的,我使用的是python 2.7,而不是从对象继承。
>>> c = Celsius(20)
>>> c.temperature
Celsius:get_temperature
20
>>> c.temperature = 40
Celsius:set_temperature
>>> c.temperature
Celsius:get_temperature
40