I am new do python OOP.
I have a problem that I can't solve by myself and even after hours of consulting the internet I am not a single step closer to an solution.
I have a linear class hierarchy where classes inherit parent classes.
For example:
class Animal:
food = "everything"
class Carnivore(Animal) :
food = "flesh"
class Wolf(Carnivore) :
food = "big animals"
class Dog(Wolf) :
food = "dog food"
Pretty simple. Each class is inheriting from another class and has the same attribute, which gets overwritten each time.
Now I want a single function, to get all the values of food.
This function should be recursive. I am thinking of something like this :
def get_food(self) :
print(self.food)
super().get_food()
Which then can be called like:
Dog.get_food()
The problem is, that the instance using the function never changes. This means I will always get "dog food" as an answer.
Is there any way to iterate throuhg all parent classes with a single function and get their attribute?
I dont want the same function written in all classes with a statement like:
print(Wolf.food)
For a easier maintenance.
Many thanks for any help or advice.
Edit:
The expected outcome for the call:
Dog.get_food()
would be :
dog food
big animals
flesh
everything