Differences Between Python and C++ Constructors

Viewed 2797

I've been learning more about Python recently, and as I was going through the excellent Dive into Python the author noted here that the __init__ method is not technically a constructor, even though it generally functions like one.

I have two questions:

  1. What are the differences between how C++ constructs an object and how Python "constructs" an object?

  2. What makes a constructor a constructor, and how does the __init__ method fail to meet this criteria?

4 Answers

The difference is owing to Python's dynamic typing. Unlike C++ where variables are declared with types and allocated in memory, Python's variables are created when assigned at run time. C++ no-arg constructors are automatically called so that they can initialize data members. In Python, it is done on demand and __init__ is looked up by the inheritance tree, only the lowest one is called and once. If a superclass data attribute is needed, super().__init__() is explicitly called like C++ initialization list. Below is an example where Base.s is initialized:

class   Base:
    def __init__(self, base):
        print("Base  class init called")
        self.base = base
class   Super(Base):
    def __init__(self, base):
        print("Super class init called")
        #super(Super, self).__init__(base)
        super().__init__(base)
class   Sub(Super):
    def __init__(self, base):
        print("Default __init__ is called")
        super().__init__(base)

sub = Sub({"base3": 3, "base4": 4})
print(sub.__dict__, sub.base)

Output:

Default __init__ is called
Super class init called
Base  class init called
{'base': {'base3': 3, 'base4': 4}} {'base3': 3, 'base4': 4}

Also, init is just like an ordinary function and can be called afterwards as such:

Sub.__init__(sub, 'abc')
print(sub.__dict__, sub.base)

Output:

Default __init__ is called
Super class init called
Base  class init called
{'base': 'abc'} abc
Related