I've googled and played a while but with no results trying to do something like this:
class A(object):
cl_att = 'I am an A class attribute'
class B(A):
cl_att += ' modified for B type'
class C(A):
cl_att += ' modified for C type'
instA = A()
print insAt.cl_att
>>> I am an A class attribute
instB = B()
print instB.cl_att
>>> I am an A class attribute modified for B type
instC = C()
print instC.cl_att
>>> I am an A class attribute modified for C type
print instA.cl_att
>>> I am an A class attribute
In short words I want to be able to "use and then override" a class attribute from my parent class.
Reference the parent class attribute and concatenate to it:
class A(object):
cl_att = 'I am an A class attribute'
class B(A):
cl_att = A.cl_att + ' modified for B type'
class C(A):
cl_att = A.cl_att + ' modified for C type'
Class bodies are executed much like functions, with the local names forming the class attributes. cl_att doesn't exist in the new 'function' to create the bodies for B and C, so you need to reference the attribute on the base class directly instead.
Demo:
>>> class A(object):
... cl_att = 'I am an A class attribute'
...
>>> class B(A):
... cl_att = A.cl_att + ' modified for B type'
...
>>> class C(A):
... cl_att = A.cl_att + ' modified for C type'
...
>>> A.cl_att
'I am an A class attribute'
>>> B.cl_att
'I am an A class attribute modified for B type'
>>> C.cl_att
'I am an A class attribute modified for C type'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With