Saturday 7 August 2021

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means creating sub-classes, which add different behaviour to the class they inherit from (or extended class, in Java nomenclature).

Suppose we have a class like this:

class Runner:
    def __init__(self):
        self.shoes = True
    def hasShoes(self):
        return self.shoes

We can create an object of this class and call the method hasShoes on it:

# !/usr/bin/python3

class Runner:
    def __init__(self):
        self.shoes = True
    def hasShoes(self):
        return self.shoes

def main():

    myRunner = Runner()
    print(myRunner.hasShoes())

if __name__ == "__main__":
    main()

The code results in:

True

Now let's extend this class by creating a subclass (LongDistanceRunner) and adding a method there - and let's create an instance of subclass and call this method:

# !/usr/bin/python3

class Runner:
    def __init__(self):
        self.shoes = True
    def hasShoes(self):
        return self.shoes

class LongDistanceRunner(Runner):
    def run(self):
            if self.hasShoes():
                print("Running slowly")
            else:
                print("Not running (no shoes)")

def main():

    myRunner = Runner()
    print(myRunner.hasShoes())

    ldRunner = LongDistanceRunner()
    ldRunner.run()
    print(ldRunner.hasShoes())


if __name__ == "__main__":
    main()

The code results in:

True
Running slowly
True

As we can see, we can call both run() - which is method from the subclass (LongDistanceRunner) and hasShoes() which is method defined in superclass ( Runner ) on the object of class LongDistanceRunner. What' more - in the class LongDistanceRunner (in the method run() ) we can use our superclass features (in this case: the method hasShoes() ).

Now let's add another class inheriting from Runner :

# !/usr/bin/python3

class Runner:
    def __init__(self):
        self.shoes = True
    def hasShoes(self):
        return self.shoes

class LongDistanceRunner(Runner):
    def run(self):
            if self.hasShoes():
                print("Running slowly")
            else:
                print("Not running (no shoes)")

class ShortDistanceRunner(Runner):
    def run(self):
            if self.hasShoes():
                print("Running fast")
            else:
                print("Not running (no shoes)")
def main():

    myRunner = Runner()
    print(myRunner.hasShoes())

    ldRunner = LongDistanceRunner()
    ldRunner.run()
    print(ldRunner.hasShoes())

    sdRunner = ShortDistanceRunner()

if __name__ == "__main__":
    main()

We can add both our "runners" to a collection and call the method  hasShoes() on both of them:

# !/usr/bin/python3

class Runner:
    def __init__(self):
        self.shoes = True
    def hasShoes(self):
        return self.shoes

class LongDistanceRunner(Runner):
    def run(self):
            if self.hasShoes():
                print("Running slowly")
            else:
                print("Not running (no shoes)")
    def drinkWater(self):
        print("Drinking water (while running)")

class ShortDistanceRunner(Runner):
    def run(self):
            if self.hasShoes():
                print("Running fast")
            else:
                print("Not running (no shoes)")
    def drinkWater(self):
        print("Drinking water (not while running)")
def main():

    myRunner = Runner()
    print(myRunner.hasShoes())

    ldRunner = LongDistanceRunner()
    ldRunner.run()
    print(ldRunner.hasShoes())

    sdRunner = ShortDistanceRunner()

    runners = [ldRunnersdRunner]

    print("Do runners have shoes?")
    for runner in runners:
        print(runner.hasShoes())
        
if __name__ == "__main__":
    main()

Which results in:

True
Running slowly
True
Do runners have shoes?
True
True

What's interesting here is that the hasShoes() method works "polymorphic" here - although it's not defined in the superclass. This behaviour is what differs polymorphism in Python from Java, C# or C++ - in all these languages polymorphism is strictly connected to inheritance.

No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...