Do I have to write myself to call the constructor of the parent class?

Asked 2 years ago, Updated 2 years ago, 89 views

Is this the only way to call a parent class constructor in a structure where C inherits B and B inherits A?

class A(object):
    def __init__(self):
        print "Creator A"

class B(A):
    def __init__(self):
        super(B,self).__init__()
        print "Creator B"

class C(B):
    def __init__(self):
        super(C,self).__init__()
        print "Generator C"

c = C()

super(B,self).__init__() Instead of explaining who you are in each class,

super(self.I want it to be a little mechanical, like __class__, self)

super(self.If you write __class__, self), self when calling super from B.__class___ is still C, so I can't write it

I'm not going to do multiple inheritance, so I don't want to talk about multiple inheritance.

inheritance oop constructor python

2022-09-22 16:09

1 Answers

In 3.x, you can simply write super()._init__(args), but in 2.x, there is no way.

and super(B,self).Writing like __init__() is actually something that fits the Python philosophy.

PEP 20 -- From The Zen of Python

... Explicit is better than implicit ...

There's a line like this (It's better to make it visible than invisible)


2022-09-22 16:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.