How do i use method overrides in python classes?



  • Also see: https://www.lightnetics.com/post/9886

    In the above article, we saw how inheritance works.

    What if we need to use a method in the child class, that overrides the parent class?

    We have the following code to start with:

    class Cake(object):
        def __init__(self):
            print("You created the cake instance")
    
        def ovenstart(self):
            print("Oven started")
    
        def ovenstop(self):
            print("Oven stopped")
    
    class Bread(Cake):
        def __init__(self):
            Cake.__init__(self)
            print("Ready, Steady, Bake!")
    
    c1 = Cake()
    c1.ovenstart()
    c1.ovenstop()
    
    b1 = Bread()
    b1.ovenstart()
    b1.ovenstop()
    

    In the code above, Let's say we wanted to override the method "ovenstart" in the parent Cake class and use something else in the Bread class.

        def ovenstart(self):
            print("Oven started")
    

    This can be done by defining another method using the same method name.

    class Cake(object):
        def __init__(self):
            print("You created the cake instance")
    
        def ovenstart(self):
            print("Oven started")
    
        def ovenstop(self):
            print("Oven stopped")
    
    class Bread(Cake):
        def __init__(self):
            Cake.__init__(self)
            print("Ready, Steady, Bake!")
       
        def ovenstart(self):
            print("Oven started for baking bread")
    
    c1 = Cake()
    c1.ovenstart()
    c1.ovenstop()
    
    b1 = Bread()
    b1.ovenstart()
    b1.ovenstop()
    

    When you run the code above you now see the following:

    You created the cake instance
    Ready, Steady, Bake!
    Oven started for baking bread >>> This is the override for ovenstart
    Oven stopped

    In another artcle we'll show how you can make the parent classes ovenstart method always execute as the master code, using the super method.


Log in to reply
 

© Lightnetics 2024