Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Class Attributes and Subclassing

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.

like image 371
Hrabal Avatar asked Dec 11 '25 21:12

Hrabal


1 Answers

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'
like image 62
Martijn Pieters Avatar answered Dec 13 '25 11:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!