为什么需要在构造函数内部调用超类?

时间:2019-07-13 09:32:10

标签: python-3.x apache-beam

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

Why does custom Python object cannot be used with ParDo Fn?

我了解到network sockets不可序列化,因为不是对象在序列化后既不返回 string 也不返回 tuple

我不明白的是,为什么需要在super class内调用__init__

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()

谢谢。

2 个答案:

答案 0 :(得分:1)

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

当您在子类中重写该方法时,不会自动调用父类__init__方法(对于其他方法,该方法的工作方式相同),因此您需要明确地称呼它。

答案 1 :(得分:1)

您的课程继承自beam.DoFn。大概该类需要在其__init__方法中进行一些设置,否则它将无法正常工作。因此,如果覆盖__init__,则需要调用父类的__init__,否则您的实例可能无法正常工作。

我会注意到您当前的super通话实际上是小虫虫。使用self.__class__作为super的第一个参数是不合适的。您要么需要显式写出当前类的名称,要么根本不传递任何参数(super的无参数形式仅在Python 3中有效)。目前暂时可以使用self.__class__,但是如果您进一步继承PublishFn的子类,并在孙类中再次覆盖__init__,它将中断。