如何将所有参数从初始化传递到超级类

2024-05-18 11:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在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: __init__() takes at most 2 arguments (3 given)


Tags: testselfverbose参数initdef情况params
1条回答
网友
1楼 · 发布于 2024-05-18 11:41:37

你就快到了:

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中获取它们。

^{} method从字典中移除键(如果存在),返回关联的值,或者如果缺少指定的默认值。这意味着我们不会把verbose传递给超级类。如果只想检查参数是否已设置,而不删除它,请使用kwargs.get('verbose', True)

相关问题 更多 >