2

I am just wondering how can I use read-only property and set initial values in __init__

I would like to have something like this: Simply private (as much a python enables privacy) variable which is set in constructor.

class A:
    def __init__(self, value: int):
         self.value = value

    @property
    def value(self):
        return self.value

As far I know this is not possible (cannot set the value)?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Newbie
  • 462
  • 7
  • 15
  • [does-python-have-private-variables-in-classes](https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes) – Patrick Artner Nov 03 '18 at 18:02

1 Answers1

2

Functions are 1st class citizens in python. You cant have two members in your class that are named exactly the same. Essentially your class already has a self.value of type <class 'property'> that your code tries to set to a integer given as value which is forbidden - so this error pop up.

Circumvent it by:

class A:
    def __init__(self, value: int):
         self._value = value  # private backer

    @property
    def value(self):
        return self._value 

my_a = A(22)       # works, no error
print(my_a.value)  # 22
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Single underscore `self._value` would be better choice here. The double underscore would invoke name mangling. – wim Nov 03 '18 at 18:07
  • 2
    No, not really. That feature is intended for preventing name collisions in inheritance situations, the single underscore is the correct convention for "not public API". – wim Nov 03 '18 at 18:09