Newbie
Newbie

Reputation: 472

How to set a read-only @property in __init__

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)?

Upvotes: 2

Views: 673

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

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

Upvotes: 2

Related Questions