Modifying child class behavior from the parent class

Posted by Afsal on 03-Mar-2023

Hi Pythonistas!

We know that languages that support OOP allow us to modify(override) existing functions in a parent from a child. But it is rare to see the opposite case. Today we are going to learn a magic method (dunder method), which will allow you to modify/restrict a property of a class from its parent. This magic method used for this is  __init_subclass__. Let us learn with an example.


class Greeting:
    def __init_subclass__(cls, **kwargs):
        cls.say = lambda: print(f'Hello world')

class HelloWorld(Greeting):
    def say(cls):
        print("Hola world")


Expected Result

Hola world

Actual Result

Hello world

Here in this example we have Greeting which is the parent class and HelloWold Child class. There is a class method called say is defined in the child class. But we have written a __init_subclass__ method in that function we defined say the method always prints hello world.

Which means the property of the child is controlled by its parent. This can be useful where we write third-party tools but we need some control over child creation.

Hope you have learned a new thing from this post. Please share your suggestions, doubts, and topics you want to learn with