简体   繁体   English

Python - 如何使用基础 class 中的方法获取派生 class 的属性

[英]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.假设我有一只从动物 class 继承的狗 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)这基本上就是我想要的:(我得到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.我知道我可以调用Dog.noise来做同样的事情,但如果可能的话,我想知道如何使用一种方法来做到这一点。 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.我也知道我可以在Dog中创建一个get_noise方法并返回Dog.noise ,但为每种类型的动物创建此方法而不是仅从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.您需要classmethod以正确地使该方法可以从实例和类中调用,并且它还可以方便地传入当前 class ,您可以从中访问.noise属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在派生类中引用基类'属性? - How to reference a base class' attribute in derived class? Python:在基类中使用派生类属性 - Python: Using derived class attributes in base class 在Python中从派生类方法调用基类方法 - Calling a base class method from a derived class method in Python 如何从python中相同的重载派生类方法中调用基类方法? - How do I call a base class method from within the same overloaded derived class method in python? Python 3:如何为派生类编写__iter__方法,以便它扩展基类的__iter__方法的行为 - Python 3: How to write a __iter__ method for derived class so that it extends on the behaviour of the base class' __iter__ method 如何在 python 的派生 class 中调用具有相同名称方法的基本 class 的方法? - How to call a method of base class with same name method in derived class in python? Python:在基类的方法中初始化新的派生类 - Python: Initialising a new derived class in a method of a base class 从派生类对象python调用基类的方法 - Call method of base class from derived class object python 来自基础类的pdb,进入派生类的方法 - pdb from base class, get inside a method of derived class 如何在Python3的基类中访问派生类的类属性? - How to access class attributes of a derived class in the base class in Python3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM