简体   繁体   English

Python 多级 inheritance 仅初始化基础 class

[英]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.在这里我正在初始化 B class 但在这种情况下我想单独初始化基数 class A。 how can i do that?我怎样才能做到这一点?

The super() function has a two-argument form. super() function 有两个参数形式。

 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 .如果给定两个 arguments typeobjsuper返回一个绑定 object 表示obj的一个版本,其超类解析将从type开始。 Normally, super().__init__() in C is basically equivalent to super(C, self).__init__() .通常, C中的super().__init__()基本上等同于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 .但是您可以提供B作为方法解析的起点,以便仅考虑 MRO 中比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.如果您正在部分初始化 object 并尝试对它的父类之一进行猴子修补,那么这是一个很好的迹象,表明C不应该是B的子类,或者您的体系结构有更大的缺陷。 So, generally, if you find yourself in this situation, consider refactoring.所以,一般来说,如果您发现自己处于这种情况,请考虑重构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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