我正在尝试学习关于 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
打印语句也可见。 属性
是否无法正常工作?
最佳答案
您尝试做的事情只适用于新型类(class)。要在 Python 2 中声明一个新式类,你需要有
class Celsius(object):
代替
class Celsius:
在 Python 3 中,所有类都是新式的,所以普通的 class Celsius
工作正常。
关于python - 属性(property)没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851062/