如何将所有参数从__init__传递给超类 [英] How to pass all arguments from __init__ to super class

查看:414
本文介绍了如何将所有参数从__init__传递给超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

IS there any magic I can use in Python to to effectively use super constructor by just adding some extra arguments?

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

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)

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

I'm using Python 2.6, but if the magic can only be achieved in higher version of Python then I'm interested too.

编辑:我应该提到上面的内容不起作用。错误是: TypeError:__ init __()最多需要2个参数(给定3个)

I should probably mention that above doesn't work. The error is: TypeError: __init__() takes at most 2 arguments (3 given)

推荐答案

你几乎就在那里:

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有点混乱 * args ** kwargs 和其他命名关键字参数;你最好的选择是添加额外的显式关键字参数,而只需从 kwargs 中获取它们。

Python 2 is a little persnickety and funny about mixing *args, **kwargs and additional named keyword arguments; your best bet is to not add additional explicit keyword arguments and just take them from kwargs instead.

dict.pop()方法从字典中删除密钥(如果存在),返回关联值,或者如果缺少我们指定的默认值。这意味着我们 verbose 传递给超类。使用 kwargs.get('verbose',True)如果您只想检查参数是否已设置而未将其删除。

The dict.pop() method removes the key from the dictionary, if present, returning the associated value, or the default we specified if missing. This means that we do not pass verbose on to the super class. Use kwargs.get('verbose', True) if you just want to check if the paramater has been set without removing it.

这篇关于如何将所有参数从__init__传递给超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆