【问题标题】:Is it a good idea to use property getter as constant variable for a class使用属性获取器作为类的常量变量是个好主意吗
【发布时间】:2020-01-14 06:20:35
【问题描述】:

因为 Python 没有 const 类型。我在一个类中有一些我不想修改的属性。

那么将属性定义为属性并且只给它一个getter而不给它一个setter是一个好主意吗?如果不是,那是什么问题?

class Aclass:
    def __init__(self):
        # do some init

    @property
    def constA(self):
        return 'abc'

非常感谢。

J

【问题讨论】:

标签: python


【解决方案1】:

来自docs

这个 [@property] 可以使用 property() 作为装饰器轻松创建只读属性。

【讨论】:

    【解决方案2】:

    这并没有错。常规代码如下所示:

    class Aclass:
        def __init__(self):
            # the underscore implies that the attribute is private
            self._constA = 'abc'
    
        @property
        def constA(self):
            return self._constA
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多