简体   繁体   中英

How to exclude __init__ of parent class but include __init__ of parent of parent class?

Is there any way possible that the Third class can inherit the First class, as well as methods of Second class except the __init__ method of Second class?

class First(object):
    def __init__(self):
        super().__init__()
        print("first")

    def f1(self):
        print("f1")


class Second(First):
    def __init__(self):
        super().__init__()
        print("second")

    def f2(self):
        print("f2")


class Third(Second):
    def __init__(self):
        super().__init__()
        print("third")
        self.f1()
        self.f2()
        self.f3()

    def f3(self):
        print("f3")


Third()

Current output

first
second
third
f1
f2
f3

Expecting output

first
third
f1
f2
f3

Third is already overriding the __init__ method, so all you have to do is use the explicit class name whose __init__ you want to use instead of calling super .

# Inside Third.__init__
First.__init__(self)

Classes can inherit from multiple parents, not only via nesting - see the MultiDevrived example here: https://www.programiz.com/python-programming/multiple-inheritance .

You would declare with Third(First, Second) so that methods from First are used before those of Second in case of naming collisions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM