Python 如何用继承扩展init方法

Python 如何用继承扩展init方法,python,Python,我有以下代码,在其中我试图扩展BaseExporter的init方法: from apps.ingest.platform_export import BaseExporter class Vudu(BaseExporter): def __init__(self): BaseExporter.__init__() self.platform = ' Vudu' 基本上,我希望所有来自BaseExporter的init'd变量加上附加变量self.p

我有以下代码,在其中我试图扩展
BaseExporter
init
方法:

from apps.ingest.platform_export import BaseExporter

class Vudu(BaseExporter):

    def __init__(self):
        BaseExporter.__init__()
        self.platform = ' Vudu'

基本上,我希望所有来自BaseExporter的init'd变量加上附加变量
self.platform='Vudu'
。我怎样才能正确地做到这一点呢?

您的思路是正确的,只是在父类中缺少了self

from apps.ingest.platform_export import BaseExporter

class Vudu(BaseExporter):

    def __init__(self):
        BaseExporter.__init__(self)
        self.platform = ' Vudu'
Python 3

from apps.ingest.platform_export import BaseExporter

class Vudu(BaseExporter):
    def __init__(self):
        super().__init__()
        self.platform = ' Vudu'
Python 2

from apps.ingest.platform_export import BaseExporter

class Vudu(BaseExporter):
    def __init__(self):
        super(Vudu, self).__init__()
        self.platform = ' Vudu'

我相信使用super是“更”正确的-因为即使类被重构为多重继承(例如多重继承),代码也会工作。我更喜欢为每个init使用父类,因为它可能有多个参数,在多重继承中甚至更多,在这种情况下,您应该使用变量参数列表。使用super可以确保继承树始终以正确的方式执行。如果我没有错,这是一种老方法。或者,如果OP使用python3,只需
super()。\uuuuu init\uuuu()