简体   繁体   中英

Python multilevel inheritance initialize only the base class

class A:
    def __init__(self) -> None:
        print("s")

class B(A):
    def __init__(self) -> None:
        print("s1")
        super().__init__()


class C(B):
    def __init__(self) -> None:
        super().__init__()

C()

Here i am initializing the B class but i want to initialize the base class A alone in this case. how can i do that?

The super() function has a two-argument form.

 super([type[, object-or-type]])

If given two arguments type and obj , super returns a bound object representing a version of obj whose superclass resolution will begin at type . Normally, super().__init__() in C is basically equivalent to super(C, self).__init__() . But you can supply B as the starting point for method resolution to only consider things further in the MRO than B .

class C(B):
    def __init__(self) -> None:
        super(B, self).__init__()

That being said, there are very few use cases for this. If you're partially initializing an object and trying to monkeypatch one of its parents, then that's a very good sign that C should not be a subclass of B , or that your architecture has bigger flaws. So, generally, if you find yourself in this situation, consider refactoring.

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