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

Python 如何将所有参数从_init__传递给超类,python,inheritance,variadic-functions,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 "

在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)
然后能够使用原始构造函数参数和我的类中的一些额外内容。像这样:

zip = ZipArchive('test.zip', 'w')
zip = ZipArchive('test.zip', 'w', verbose=False)
我使用的是Python2.6,但如果这种魔力只能在更高版本的Python中实现,那么我也很感兴趣

编辑:我可能应该提一下,上面的内容不起作用。错误是:
TypeError:\uuuu init\uuuu()最多接受2个参数(给定3个)

您就快到了:

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)
Python2在混合
*args
**kwargs
和其他命名关键字参数方面有点挑剔和有趣;您最好的选择是不要添加额外的显式关键字参数,而只是从
kwargs
中获取它们


从字典中删除键(如果存在),返回关联的值,如果缺少,则返回我们指定的默认值。这意味着我们不把
verbose
传递给超类。使用<代码> kWAG.获取('VBBOSE,TRUE)< /代码>,如果您只想检查PARAMATER是否已被设置而不删除它。 > VBBOSE=KWARGS.POP(“VBBOSE”,VBBORE Debug值)@ GLGLL:实际上,我忘了<代码> POP()>代码>默认。您可能还想考虑<代码> Self.VBBOSE=KWGG.GET。('verbose',verbosedefaultvalue)以防您想查看也执行超类方法的参数。这在参数方面似乎确实有效,但我得到的是
TypeError:super()参数1必须是type,而不是classobj
。据我所知,我不能继承
zipfile.zipfile
并使用
super
,因为原始类是一个旧式类:-(.至少在Python 2.6.6上是这样。但谢谢你,我会在其他情况下使用它。@Nux:Then
zipfile.zipfile.\uu init_uu(self,*args,**kwargs)
将起作用;同样的原则也适用。