3

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

J_yang
  • 2,672
  • 8
  • 32
  • 61
  • Nothing wrong with that. – James Sep 12 '19 at 11:22
  • It can only be called from instances, not from the class which seems semantically questionable. See https://stackoverflow.com/questions/3203286/how-to-create-a-read-only-class-property-in-python/26634248 for a different approach – user2390182 Sep 12 '19 at 11:28

2 Answers2

3

From the docs

This [@property] makes it possible to create read-only properties easily using property() as a decorator.

gboffi
  • 22,939
  • 8
  • 54
  • 85
2

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
BramAppel
  • 1,346
  • 1
  • 9
  • 21