[英]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.