为了账号安全,请及时绑定邮箱和手机立即绑定

关于在 Python 中的同一类属性中是否使用下划线

关于在 Python 中的同一类属性中是否使用下划线

紫衣仙女 2021-11-30 18:27:52
为什么在这个例子中,有时作者对同一个属性使用self._temperatureand self.temperature(带和不带下划线)?class Celsius:    def __init__(self, temperature = 0):        self._temperature = temperature    def to_fahrenheit(self):        return (self.temperature * 1.8) + 32    @property    def temperature(self):        print("Getting value")        return self._temperature    @temperature.setter    def temperature(self, value):        if value < -273:            raise ValueError("Temperature below -273 is not possible")        print("Setting value")        self._temperature = value
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

这里使用了两个单独的属性。_temperature实例属性,temperature而是属性,其值为property对象。访问temperature会触发一个作用于实例变量的方法调用_temperature

下划线的使用表示某些内容是“私有的”,不应直接访问。支持属性的属性名称是带有前缀的属性名称,这是一种常见约定_


查看完整回答
反对 回复 2021-11-30
  • 1 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信