1

Just for instance,

c = myClass()
  1. Attribute x of myClass is readonly. Trying to change c.x raises an error.

  2. Attributes a and b of myClass are connected by a=2*b. When one changes, the other changes automatically too.

c.a = 10 
# or setattr(c,'a',10) or c.__setattr('a',10)
# c.b becomes 5
c.b = 10
# c.a becomes 20
Lee
  • 526
  • 3
  • 9

1 Answers1

4

What you are looking for is @property.

class MyClass:
    def __init__(self, x, a):
        self._x = x
        self.a = a

    @property
    def x(self):
        return self._x

    @property
    def b(self):
        return self.a / 2

    @b.setter
    def b(self, b):
        self.a = b * 2

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

Quentin Roy
  • 7,677
  • 2
  • 32
  • 50