I have a project with the following class structure:
class A(object):
elems = [1, 2, 3]
class B(A):
pass
class C(B):
elems = [20, 100]
class D(B):
elems = [4, 5]
Currently, Python’s default inheritance behaviour is to overwrite the elems attribute in each subsequent attribute declaration, e.g.:
A.elems == [1, 2, 3]
B.elems == [1, 2, 3]
C.elems == [20, 100]
D.elems == [4, 5]
I would like to be able to access an additive list of these values. In other words, I would like to be able to retrieve the following lists:
A.collated() == [1, 2, 3]
B.collated() == [1, 2, 3]
C.collated() == [1, 2, 3, 20, 100]
D.collated() == [1, 2, 3, 4, 5]
I don’t know how to do this. Any help would be greatly appreciated.
Thanks in advance,
– B
The easiest solution here is to just be explicit:
There are tricky things you could do to make this more automatic, but I don’t think you want to. (If you think you want to, first go read up on how either descriptors or metaclasses work, then come back with specific questions.)