为什么需要在构造函数中调用 super class ?

Why do you need to call super class inside constructor?

如果有人能帮助我理解下面问题中的代码示例,我将不胜感激。我现在正在尝试使用 apache beam 2.13.0python3.7.3.

来实现类似的事情

我知道 network sockets 不可序列化,因为它不是对象 return 既 string 也不 tuple连载后

我不明白的是为什么要在__init__里面调用super class

class PublishFn(beam.DoFn):
    def __init__(self, topic_path):
        self.topic_path = topic_path
        super(self.__class__, self).__init__()

    def process(self, element, **kwargs):
        if not hasattr(self, 'publish'):
            from google.cloud import pubsub_v1
            self.publisher = pubsub_v1.PublisherClient()
        future = self.publisher.publish(self.topic_path, data=element.encode("utf-8"))
        return future.result()

谢谢。

显然,父 class 的 __init__ 方法进行了一些初始化,这是 class 实例正常运行所必需的。如果您 调用此方法,您的代码可能会中断,因为 class 无法正确初始化。

父 class 的 __init__ 方法 不会 当您覆盖子 class 中的方法时自动调用(它有效其他方法同理),所以需要显式调用。

您的 class 继承自 beam.DoFn。想必 class 需要在它的 __init__ 方法中设置一些东西,否则将无法正常工作。因此,如果您覆盖 __init__,您需要调用父 class 的 __init__,否则您的实例可能无法按预期运行。

我注意到您当前的 super 调用实际上存在细微的错误。使用 self.__class__ 作为 super 的第一个参数是不合适的。您要么需要显式写出当前 class 的名称,要么根本不传递任何参数(super 的 no-argument 形式仅在 Python 3 中有效) .使用 self.__class__ 可能暂时有效,但如果您进一步 subclass PublishFn 并在孙子 class 中再次覆盖 __init__,它将中断。