简体   繁体   English

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

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

Since Python has no const type. 由于Python没有const类型。 I have some attributes in a class that I do not wish to be modified. 我在类中有一些不希望被修改的属性。

So is it a good idea to define the attributes as property and only give it a getter without a setter? 那么将属性定义为属性并只给它一个不带setter的getter是一个好主意吗? If not what is the issue? 如果不是,那是什么问题?

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

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

Many thanks. 非常感谢。

J Ĵ

From the docs 来自文档

This [ @property ] makes it possible to create read-only properties easily using property() as a decorator. 这个[ @property ]可以使用property()作为修饰符轻松地创建只读属性。

There is nothing wrong with that. 没有什么不妥。 The conventional code looks like this: 常规代码如下所示:

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