Search code examples
pythonclassparent-childstatic-variablesstatic-classes

Accessing class attributes in base (parent) class method with possible overloading by derived (children) classes


I am trying to create a function in a parent class that references which ever child class ends up calling it in order to get a static variable that is in the child class.

Here is my code.

class Element:
  attributes = []

  def attributes_to_string():
    # do some stuff
    return ' | '.join(__class__.attributes) # <== This is where I need to fix the code.

class Car(Element):
  attributes = ['door', 'window', 'engine']

class House(Element):
  attributes = ['door', 'window', 'lights', 'table']

class Computer(Element):
  attributes = ['screen', 'ram', 'video card', 'ssd']

print(Computer.attributes_to_string())

### screen | ram | video card | ssd

I know how I would do this if it were an instance of the class using self.__class__, but there is no self to reference in this case.


Solution

  • decorating with classmethod should work

    class Element:
        attributes = []
    
        @classmethod
        def attributes_to_string(cls):
            # do some stuff
            return ' | '.join(cls.attributes)
    
    
    class Car(Element):
        attributes = ['door', 'window', 'engine']
    
    
    class House(Element):
        attributes = ['door', 'window', 'lights', 'table']
    
    
    class Computer(Element):
        attributes = ['screen', 'ram', 'video card', 'ssd']
    
    
    print(Computer.attributes_to_string())
    

    gives us

    screen | ram | video card | ssd