繁体   English   中英

将属性获取器用作类的常量是一个好主意吗

[英]Is it a good idea to use property getter as constant variable for a class

由于Python没有const类型。 我在类中有一些不希望被修改的属性。

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

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

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

非常感谢。

Ĵ

来自文档

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

没有什么不妥。 常规代码如下所示:

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

    @property
    def constA(self):
        return self._constA

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM