【问题标题】:Why do you need to call super class inside constructor?为什么需要在构造函数中调用超类?
【发布时间】:2019-07-13 09:32:10
【问题描述】:

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

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

我知道network sockets 是不可序列化的,因为它不是在序列化之后既不能返回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()

谢谢。

【问题讨论】:

    标签: python-3.x apache-beam


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-11-23
        • 2022-01-19
        • 2018-06-02
        • 1970-01-01
        • 2020-03-10
        • 1970-01-01
        • 2017-12-18
        • 2021-06-17
        相关资源
        最近更新 更多