Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Constructor Chaining and Polymorphism [duplicate]

Tags:

python

oop

I'm trying to learn Python's OOP standards, I've written a very simple code

class Human(object):
    def __init__(self):
        print("Hi this is Human Constructor")

    def whoAmI(self):
        print("I am Human")


class Man(Human):
    def __init__(self):
        print("Hi this is Man Constructor")

    def whoAmI(self):
        print("I am Man")


class Woman(Human):
    def __init__(self):
        print("Hi this is Woman Constructor")

    def whoAmI(self):
        print("I am Woman")

Seems pretty simple eh? Classic inheritance module of man and woman, what i can't understand is that when i create an object for woman or man why doesn't the constructor chaining occurs, and how one could possibly achieve polymorphism in Python.

This seems like a real vague and noob line of questioning, but i'm unable to put it any other way. Any help will be appreciated

like image 755
Mirza Talha Avatar asked Sep 07 '25 14:09

Mirza Talha


1 Answers

You have a __init__() for Man as well as Woman , so that overrides the __init__() from the parent class Human . If you want the __init__() for child class to call the parent's __init__() , then you need to call it using super(). Example -

class Man(Human):
    def __init__(self):
        super(Man, self).__init__()
        print("Hi this is Man Constructor")

class Woman(Human):
    def __init__(self):
        super(Woman, self).__init__()
        print("Hi this is Woman Constructor")

For Python 3.x , you can simply call the parent's __init__() using - super().__init__() .

like image 152
Anand S Kumar Avatar answered Sep 10 '25 05:09

Anand S Kumar