如何将所有参数从__init__传递给超类

Nux*_*Nux 11 python inheritance variadic-functions

我是否可以在Python中使用任何魔法来通过添加一些额外的参数来有效地使用超级构造函数?

理想情况下,我想使用类似的东西:

class ZipArchive(zipfile.ZipFile):
    def __init__(self, verbose=True, **kwargs):
        """
        Constructor with some extra params.

        For other params see: zipfile.ZipFile
        """
        self.verbose = verbose
        super(ZipArchive, self).__init__(**kwargs)
Run Code Online (Sandbox Code Playgroud)

然后能够使用原始的构造函数参数与我的类中的一些额外的东西混合.像这样:

zip = ZipArchive('test.zip', 'w')
zip = ZipArchive('test.zip', 'w', verbose=False)
Run Code Online (Sandbox Code Playgroud)

我正在使用Python 2.6,但如果魔法只能在更高版本的Python中实现,那么我也很感兴趣.

编辑:我应该提到上面的内容不起作用.错误是:TypeError: __init__() takes at most 2 arguments (3 given)

Mar*_*ers 25

你快到了:

class ZipArchive(zipfile.ZipFile):
    def __init__(self, *args, **kwargs):
        """
        Constructor with some extra params:

        * verbose: be verbose about what we do. Defaults to True.

        For other params see: zipfile.ZipFile
        """
        self.verbose = kwargs.pop('verbose', True)

        # zipfile.ZipFile is an old-style class, cannot use super() here:
        zipfile.ZipFile.__init__(self, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

Python 2中是有点俗气和有趣的关于混合*args,**kwargs以及额外的命名关键字参数; 你最好的选择是添加额外的显式关键字参数,而只是从中取出它们kwargs.

dict.pop()方法从字典中删除键(如果存在),返回关联值,或者如果缺少则返回我们指定的默认值.这意味着我们不会传递verbose给超类.使用kwargs.get('verbose', True),如果你只是想检查paramater已设置而不移除它.

  • 您可能还想考虑使用“ self.verbose = kwargs.get('verbose',verbosedefaultvalue)”,以防您看到同样执行超类方法的args。 (2认同)