假设我有一对基类,其中一个实例化了另一个:
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
类。避免这种重复的最佳方法是什么?
我是否应该在 AnimalHome
和 Cattery
类上定义一个特殊的类方法 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/