'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 1:[1]

The following worked for me.

class Animal:
    noise = 'Noise'

    def get_noise(self):
        return self.noise


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


dog = Dog()
dog.get_noise()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman