pythoninheritanceclass-attributes

Python - How to get an attribute of a derived class using a method in the base class


Let's say I have a Dog class that inherits from an Animal class. I want every Animal to make a noise of some sort, and I want to be able to access this noise using a method, regardless of whether an instance of the animal exists.

This is essentially what I want: (I get NameError: name 'noise' is not defined when I try to run it)

class Animal:
    noise = ''
    def get_noise():
        return noise

class Dog(Animal):
    noise = 'Woof!'

Dog.get_noise()

I know I can just call Dog.noise to do the same thing, but I'd like to know how to do it using a method, if possible. I also know I could just create a get_noise method inside Dog and return Dog.noise but it seems inelegant to create this method for every type of animal rather than just inherit from the Animal class.

Any help appreciated!


Solution

  • You want:

    @classmethod
    def get_noise(cls):
        return cls.noise
    

    You need classmethod to properly make the method callable from both instances and classes, and it also conveniently passes in the current class from which you can access the .noise attribute.