在子 class 中初始化父 class 的要求是什么?

What are the requirements to cause an initialization of the parent class in child class?

我对 OOP 还是个新手。

在子实例 class 中,我想使用在初始化父实例 class 时设置的参数:

class parent():
    def __init__(self, config):
        self._config = config

class child(parent):  
    print self._config

x = "Hello"
c = child(x)

这不起作用,因为 self 是未知的,所以会抛出错误。我真的需要每次都从父 class 复制完整的 __init__ 块吗?我看到在某些情况下可以在没有 __init__ 块的情况下触发初始化:

class parent():
    def __init__(self, config):
        self._config = config

class child(parent):  
    # Nonsense since not itarable, but no error anymore
    def next(self):
        print self._config

x = "Hello"
c = child(x)

虽然这不起作用,但它仍然没有抛出错误。 是否有任何简短的方法来初始化子 class 中的父 class 或从父获取所有参数?

x = "Hello"
c = child(x)

此代码确实创建了 child 的实例,其中 _config = "Hello"

但是,所有 都是如此。它不会 打印 _config 的值,这似乎是您所期望的。

如果您希望 __init__ 函数打印 self._config 的值,您必须添加代码才能实现。

您可以简单地调用 parent 的 __init__,这是常见的做法:

class child(parent):
    def __init__(self, config):
        super(child, self).init(config)
        print self._config
class parent:
    def __init__(self, config):
        self._config = config

class child(parent):

    def __init__(self,config):
        parent.__init__(self,config)

    def next(self):
        print self._config

x = child("test")
x.next() # prints test

所有传递给parent的参数都必须传递给child来初始化child__init__里面的parent