Say I have an class that looks like this:
class Test(object):
def __init__(self, a, b):
self.a = a
self.b = b
self.c = self.a + self.b
The simplest solution is to make c
a read-only property:
class Test(object):
def __init__(self, a, b):
self.a = a
self.b = b
@property
def c(self):
return self.a + self.b
Now every time you access test_instance.c
, it calls the property getter and calculates the appropriate value from the other attributes. In use:
>>> t = Test(2, 4)
>>> t.c
6
>>> t.a = 3
>>> t.c
7
Note that this means that you cannot set c
directly:
>>> t.c = 6
Traceback (most recent call last):
File "", line 1, in
t.c = 6
AttributeError: can't set attribute