2016-10-04 53 views
1

我试图按照教程上http://www.programiz.com/python-programming/property,并写了下面的脚本:财产不能发挥预期

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

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

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

    temperature = property(get_temperature, set_temperature) 


c = Celsius() 

print c.temperature 
c.temperature = 100 
print c.temperature 

当我运行该脚本,我只看到了两个温度值:

0 
100 

但是,我希望Getting valueSetting value打印语句也可见。 property不知何故无法正常工作?

+0

的Python 2或Python 3? – khelwood

+0

通过设置c.temperature,你实际上并没有调用该方法set_temperature但是方法'C .__ setattr__'有以下为参数的C .__ SETATTR __(“温度”,100)。所以,你要覆盖什么是'__setattr__'方法 – dnalow

+2

如果是Python 2中,问题是,你的类不从'object'继承,因此它是一个旧式的类。将第一行更改为'class Celsius(object):' – khelwood

回答

2

你想做的事情只适用于新式课堂。在Python 2声明一个新式类,你需要有

class Celsius(object): 

代替

class Celsius: 

在Python 3,所有的类都是新型的,所以class Celsius正常工作的平原。

1

的代码应该工作原样,但你的Python混合2语法与Python 3


如果你把print报表类外进入函数调用,代码工作罚款有效的Python 3

如果你运行该像Python 2的代码,那么你必须从object继承类,并保持所有其他的事情原样。


选择一个。

1

你需要定义类,因为这:

class Celsius(object): 
    balabala 
    balabala