python - getter 和 setter 的属性装饰器

标签 python properties decorator python-decorators

我对如何在此属性装饰代码中获取和设置温度感到有点困惑。这是使用属性装饰器的正确方法吗?但是我不确定如何使用它。我可以调用 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

最佳答案

属性允许您 Hook 属性访问,并设置属性。当您分配给属性时,将调用 setter:

c = Celsius(20)
c.temperature = 40

但请注意,在 Python 2 中,您需要从 object 继承才能使属性起作用:

class Celsius(object):

演示:

>>> c = Celsius(20)
>>> c.temperature
Celsius:get_temperature
20
>>> c.temperature = 40
Celsius:set_temperature
>>> c.temperature
Celsius:get_temperature
40

关于python - getter 和 setter 的属性装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749229/

相关文章:

python - 为 sys.exit 创建单元测试

java - 在 python 中运行 java 代码 - 带输入/输出

使用 line_profiler 进行 Python 分析 - 即时删除 @profile 语句的巧妙方法?

spring - 属性文件中的 persistence.xml 属性值

java - 带有 Spring : how externalize properties file? 的 Web 应用程序

python - 装饰函数如何在 flask /python 中工作? (app.route)

python - 尝试编写一个 "to_class"通用装饰器

python - 从命令行运行 SikuliX 1.1.4 Python 脚本

python - 如何在 Tensorflow 中计算 R^2

ios - 如何更改子类中的委托(delegate)? objective-c