我试图按照教程上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 value
和Setting value
打印语句也可见。 property
不知何故无法正常工作?
的Python 2或Python 3? – khelwood
通过设置c.temperature,你实际上并没有调用该方法set_temperature但是方法'C .__ setattr__'有以下为参数的C .__ SETATTR __(“温度”,100)。所以,你要覆盖什么是'__setattr__'方法 – dnalow
如果是Python 2中,问题是,你的类不从'object'继承,因此它是一个旧式的类。将第一行更改为'class Celsius(object):' – khelwood