xnx
xnx

Reputation: 25508

What is the best way of using inheritance in two related classes

Suppose I have a pair of base classes, one of which instantiates the other:

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')

Now I want a derived AnimalHome class within which I want to use some other class of derived Animal instances:

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 ...

I have to repeat essentially the same code in the method populate_home to use the Cat class instead of the Animal class. What is the best way to avoid this repetition?

Should I define a special class method get_animal_class on the AnimalHome and Cattery classes, that simply returns the appropriate animal class:

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

in the Animal class, and

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

in the Cat class, or is there a better way?

Upvotes: 1

Views: 72

Answers (1)

AKX
AKX

Reputation: 168903

Instead of a method to instantiate the class, you can set it as a class variable:

class AnimalHome:
    animal_class = None

class Cattery(AnimalHome):
    animal_class = Cat

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

Upvotes: 4

Related Questions