简体   繁体   English

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

[英]How to pass all arguments from __init__ to super class

IS there any magic I can use in Python to to effectively use super constructor by just adding some extra arguments? 我是否可以在Python中使用任何魔法来通过添加一些额外的参数来有效地使用超级构造函数?

Ideally I'd like to use something like: 理想情况下,我想使用类似的东西:

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)

And then be able to use the original constructor arguments mixed with some extra stuff from my class. 然后能够使用原始的构造函数参数与我的类中的一些额外的东西混合。 Like so: 像这样:

zip = ZipArchive('test.zip', 'w')
zip = ZipArchive('test.zip', 'w', verbose=False)

I'm using Python 2.6, but if the magic can only be achieved in higher version of Python then I'm interested too. 我正在使用Python 2.6,但如果魔法只能在更高版本的Python中实现,那么我也很感兴趣。

EDIT: I should probably mention that above doesn't work. 编辑:我应该提到上面的内容不起作用。 The error is: TypeError: __init__() takes at most 2 arguments (3 given) 错误是: TypeError: __init__() takes at most 2 arguments (3 given)

You are almost there: 你快到了:

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)

Python 2 is a little persnickety and funny about mixing *args , **kwargs and additional named keyword arguments; Python 2对于混合*args**kwargs和其他命名关键字参数有点过于乐观和有趣; your best bet is to not add additional explicit keyword arguments and just take them from kwargs instead. 你最好的选择是添加额外的显式关键字参数,而只是从kwargs取出它们。

The dict.pop() method removes the key from the dictionary, if present, returning the associated value, or the default we specified if missing. dict.pop()方法从字典中删除键(如果存在),返回关联值,或者如果缺少则返回我们指定的默认值。 This means that we do not pass verbose on to the super class. 这意味着我们不会verbose传递给超类。 Use kwargs.get('verbose', True) if you just want to check if the paramater has been set without removing it. 如果你只是想检查参数是否已经设置而没有删除它kwargs.get('verbose', True)请使用kwargs.get('verbose', True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM