Access parent class variables from child class variables

Viewed 7740

Here's an example of what I mean:

class Duck:
  SIZE = 'Fat'

class GreenDuck(Duck):
  COLOR = 'Green'
  DESCRIPTION = SIZE + ' and '  + COLOR

>>> alien_duck = GreenDuck()
>>> print(alien_duck.DESCRIPTION)

NameError: name 'SIZE' is not defined 

>>> alien_duck.SIZE
Fat

Is there a way I can access the parent 'size' class variable from inside the class?

Also defining super().__init__() in the GreenDuck class doesn't fix it.

2 Answers

Since it's a class constant:

class GreenDuck(Duck):
    COLOR = 'Green'
    DESCRIPTION = Duck.SIZE + ' and '  + COLOR

When accessing variables from another class , class.variableName should be used instead of just variable name .

If you want to access variables within the same class (which is also present in the parent class ) , self.variableName can be used to refer to the variables defined in the scope of the current class .

Related