gpt4 book ai didi

python - 访问父类中的子类变量

转载 作者:太空狗 更新时间:2023-10-30 00:42:38 24 4
gpt4 key购买 nike

在父类中访问子类的变量是否正确?这是一个好的 OOP 方法吗?我不需要创建 Animal 类的实例,但如果我愿意,make_sound 方法将引发 AttributeError,这让我很困扰。

class Animal:
def make_sound(self):
print(self.sound)

class Cat(Animal):
sound = 'meow'

class Dog(Animal):
sound = 'bark'

cat = Cat()
cat.make_sound()

dog = Dog()
dog.make_sound()

最佳答案

这种方法本质上没有错。这实际上取决于此类的范围和重要性,以及它的使用位置。构建父类以使用隐式定义的属性很快,而且在许多情况下完全没问题。但是,有时这些隐式属性可能会失控,您可能希望确保创建新子类的任何人必须定义这些属性。

有几种方法可以解决这个问题。其中一些可能不起作用,具体取决于您使用的 Python 版本。我相信像这样使用 ABC 在 Python 3.4+ 中有效。

Python(和许多 OO 语言)有一个 Abstract Base Class 的概念.这是一个永远无法实例化的类,它强制任何子类必须实现定义为抽象的方法或属性才能被实例化。

您可以通过以下方式提供 make_sound 方法,并且仍然 100% 确定继承 Animal 的任何人确实会发出那种声音。

from abc import ABC, abstractmethod


class Animal(ABC):

def make_sound(self):
print(self.sound)

@property
@abstractmethod
def sound(self):
""" return the sound the animal makes """


class Dog(Animal):

@property
def sound(self):
return "bark"


class Cat(Animal):

sound = "meow"


class Thing(Animal):
""" Not an animal """

dog = Dog()
dog.make_sound()
cat = Cat()
cat.make_sound()
# thing = Thing() this will raise a TypeError, complaining that its abstract
# animal = Animal() as will this

这显示了执行此操作的许多不同方法。使用 @property 装饰器允许您设置影响它的实例变量或更复杂的逻辑。在类中设置声音(有点)类似于在 Java 类中设置静态成员。由于所有的猫都会喵喵叫,在这种情况下这可能是有道理的。

关于python - 访问父类中的子类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49436367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com