简体   繁体   中英

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

Since Python has no const type. 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? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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