Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用属性getter作为类的常量变量是一个好主意吗_Python - Fatal编程技术网

Python 使用属性getter作为类的常量变量是一个好主意吗

Python 使用属性getter作为类的常量变量是一个好主意吗,python,Python,因为Python没有常量类型。我不希望修改类中的某些属性 那么,将属性定义为属性,只给它一个getter而不给它一个setter,这是一个好主意吗?如果不是,问题是什么 class Aclass: def __init__(self): # do some init @property def constA(self): return 'abc' 非常感谢 J来自 此[@property]使使用property()作为装饰器轻松创建只读

因为Python没有常量类型。我不希望修改类中的某些属性

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

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

    @property
    def constA(self):
        return 'abc'
非常感谢

J

来自

此[
@property
]使使用
property()
作为装饰器轻松创建只读属性成为可能


这没什么错。常规代码如下所示:

类Aclass:
定义初始化(自):
#下划线表示该属性是私有的
self._constA='abc'
@财产
def constA(自我):
回归自我

这没什么错。它只能从实例调用,不能从语义上有问题的类调用。请参阅以了解不同的方法