4

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

Mirza Talha
  • 75
  • 1
  • 6
  • 3
    see : http://stackoverflow.com/questions/904036/chain-calling-parent-constructors-in-python – Hacketo Sep 17 '15 at 09:20
  • Some don't even like to call `__init__` a constructor, see http://stackoverflow.com/questions/6578487/init-as-a-constructor – Moberg Sep 17 '15 at 09:24

1 Answers1

6

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__() .

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • oh! languages like C# or java have this as by default, can you please help me with polymorphism? we can only create specialized object in python? – Mirza Talha Sep 17 '15 at 09:32
  • Yes, In Python if the child has the `__init__()` method, parent's `__init__()` is not called (if child does not have one, parent's `__init__()` gets called). We can create derived objects in python, like the ones you created. If the derived object does not provide an implementation of a method, but its parent object does, then when you call that method on an instance of the derived object , you get the implementation from the parent object (again, only if the child object itself, does not provide an implementation) . – Anand S Kumar Sep 17 '15 at 09:37
  • 1
    I'd say that "explicit is better than implicit" applies here – Andrea Corbellini Sep 17 '15 at 09:41
  • True :) Still, I'm happy that I can freely decide if/when/how to call the methods from the parent – Andrea Corbellini Sep 17 '15 at 09:46
  • well i'm not :) i'm a creature of habit. Have to forget old ways i suppose. – Mirza Talha Sep 17 '15 at 09:56