python - 在两个相关类中使用继承的最佳方式是什么

标签 python oop inheritance

假设我有一对基类,其中一个实例化了另一个:

class Animal:
    def __init__(self, name):
        self.name = name

class AnimalHome:
    def __init__(self, location):
        self.location = location

    def populate_home(self):
        self.animal1 = Animal(name='Rex')
        self.animal2 = Animal(name='Barney')

现在我想要一个派生的 AnimalHome 类,我想在其中使用一些其他类的派生 Animal 实例:

class Cat(Animal):
    # Interesting properties of cats defined here ...

class Cattery(AnimalHome):
    def populate_home(self):
        self.animal1 = Cat(name='Fluffy')
        self.animal2 = Cat(name='Trixie')

    # Interesting properties of Catteries defined here ...

我必须在方法 populate_home 中重复基本相同的代码,以使用 Cat 类而不是 Animal 类。避免这种重复的最佳方法是什么?

我是否应该在 AnimalHomeCattery 类上定义一个特殊的类方法 get_animal_class,它只返回适当的动物类:

def instantiate_animal(self, *args, **kwargs):
    return Animal(*args, **kwargs)

Animal 类中,并且

def instantiate_animal(self, *args, **kwargs):
    return Cat(*args, **kwargs)

Cat类中,还是有更好的方法?

最佳答案

您可以将其设置为类变量,而不是实例化类的方法:

class AnimalHome:
    animal_class = None

class Cattery(AnimalHome):
    animal_class = Cat

    # self.animal_class will be Cat in Cattery's methods

关于python - 在两个相关类中使用继承的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825833/

相关文章:

python - 多索引中的计算列

c++ - 前端/后端设计 : how to absolutely dissociate the back-end from the front-end?

C# 基类和 2 个派生类初始化

.net - Border 不继承 Control,那么 Control.Background 上的 setter 是如何工作的呢?

java - 如何从父类(super class)类型的ArrayList中获取某个子类型的对象?

python - 使用带有 logging.config 的 TimedRotatingFileHandler 日志记录

python - 使用 Python 将多个字典写入带有一个 header 的 CSV

java - 违反 OO 指导原则

python - 如何正确地向 Mixin 类添加类型提示?

python - Keras CuDNNLSTM 隐式激活函数?