Skip to content Skip to sidebar Skip to footer

How To Forbid The Assignment To Some Attributes And Update Linked Attributes Of A Python Object?

Just for instance, c = myClass() Attribute x of myClass is readonly. Trying to change c.x raises an error. Attributes a and b of myClass are connected by a=2*b. When one changes

Solution 1:

What you are looking for is @property.

classMyClass:def__init__(self, x, a):
        self._x = x
        self.a = a

    @propertydefx(self):
        returnself._x

    @propertydefb(self):
        returnself.a / 2@b.setter
    defb(self, b):
        self.a = b * 2

There is no setter for x so it is read only.

Post a Comment for "How To Forbid The Assignment To Some Attributes And Update Linked Attributes Of A Python Object?"