mightycode Newton
mightycode Newton

Reputation: 3949

composition over inheritance, even is it a Is-a relationship

I try to use composition even the relationship is: is-a.

So I have a Animal class and I have a Zebra class:


class Name:
    pass


class Age:
    pass

class Zebra():
    pass


class Animal:

    def __init__(self, name_animal, age_animal) -> None:
        self.name_animal = name_animal
        self.age_animal = age_animal
        self.name = Name()
        self.age = Age()
        self.zebra = Zebra()

    def __repr__(self):
              return "My name is {} and I am {} years old".format((self.name_animal), (self.age_animal))


zebra1 = Zebra('Zebra', 37)
print(zebra1)

but then of course it fails because Zebra has no arguments.

So is it possible to use the repr method also for Zebra without inheritcance but with compostion?

Because I get now this error:

TypeError: Zebra() takes no arguments

Upvotes: 2

Views: 71

Answers (1)

jabaa
jabaa

Reputation: 6807

I don't recommend to use composition in this case. This is a use-case for inheritance. But academic questions also deserve an answer.

Add a constructor to Zebra that initializes and stores an Animal instance and delegate __repr__:

class Animal:
    def __init__(self, name_animal, age_animal) -> None:
        self.name_animal = name_animal
        self.age_animal = age_animal

    def __repr__(self):
        return "My name is {} and I am {} years old".format((self.name_animal), (self.age_animal))

class Zebra():
    def __init__(self, name_animal, age_animal) -> None:
        self.animal = Animal(name_animal, age_animal)

    def __repr__(self):
        return self.animal.__repr__()

zebra1 = Zebra('Zebra', 37)
print(zebra1)

Upvotes: 2

Related Questions