简体   繁体   中英

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!

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM