Home > Net >  When I call C().__init__() from class D, why the result of C().__init__() gets printed twice?
When I call C().__init__() from class D, why the result of C().__init__() gets printed twice?

Time:06-14

class M(object):
    def __init__(self):
        print("M constructor")
        super().__init__()


class F(M):
    def __init__(self):
        print("F constructor")
        super().__init__()


class C(F):
    def __init__(self):

        print("C constructor")
        super().__init__()

class D(C,F):
    def __init__(self):
        print("D constructor")
        C().__init__()


D()

Output is:

D constructor
C constructor
F constructor
M constructor
C constructor
F constructor
M constructor

I was expecting:

D constructor
C constructor
F constructor
M constructor

CodePudding user response:

C().__init__() is effectively equivalent to:

temp = C()
temp.__init__()

When calling C(), the __init__() method in the C class is called automatically, so it prints C constructor and also calls all the parent constructors.

Then you call the __init__() method explicitly, so it repeats this process.

If you just want to call the C constructor without creating a temporary instance, use C.__init__(self).

CodePudding user response:

You are creating two objects in your program: a D object, and a C object (which you create in the D constructor, initialize twice by manually calling __init__() after creating the instance, and then throw away).

If you want to call C's initializer explicitly in D's initializer (rather than using super()) the correct way to do that is:

C.__init__(self)
  • Related