[英]Python - How to get an attribute of a derived class using a method in the base class
假设我有一只从动物 class 继承的狗 class。 我希望每只动物都发出某种噪音,并且我希望能够使用一种方法来访问这种噪音,而不管动物的实例是否存在。
这基本上就是我想要的:(我得到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()
我知道我可以调用Dog.noise
来做同样的事情,但如果可能的话,我想知道如何使用一种方法来做到这一点。 我也知道我可以在Dog
中创建一个get_noise
方法并返回Dog.noise
,但为每种类型的动物创建此方法而不是仅从Animal
class 继承似乎并不优雅。
任何帮助表示赞赏!
你要:
@classmethod
def get_noise(cls):
return cls.noise
您需要classmethod
以正确地使该方法可以从实例和类中调用,并且它还可以方便地传入当前 class ,您可以从中访问.noise
属性。
以下对我有用。
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.