obrazky
-

Generalization

If we look at the methods meow and bark, you might notice that we could name them in a way that allows them to be used for all animals, similar to the method eat. For example:

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

        def eat(self, food):
            print(f"{self.name}: I like {food}í!")


    class Kitty(Animal):
        def make_sound(self):
            print(f"{self.name}: Meow!")


    class Puppy(Animal):
        def make_sound(self):
            print(f"{self.name}: Woof!")


    animals = [Kitty('Micka'), Puppy('Dunčo')]

    for animal in animals:
        animal.make_sound()
        animal.eat('treat')

This example suggests that designing base classes that are easy to inherit from is not that simple. This is especially true if the inheritance is meant to be used in another program. For this reason, it is recommended to use inheritance mainly within your own code, and not to inherit from classes written by others (for example: bool, etc.), unless explicitly recommended by the author of the base class.

Úloha 1: Program a sea simulation. In the sea, there will be two types of fish – sardines and sharks. Sardines eat plankton and reproduce. Since there is plenty of plankton, sardines would eventually fill the entire sea. Sharks eat sardines. If they are well-fed, they also reproduce, but if they are not, they die.

Use inheritance in your implementation.

Download: sea_simulation.py

-
Copyright © 2008-2026 Miroslava Valíková