gpt4 book ai didi

python - 如何将所有参数从 __init__ 传递给父类(super class)

转载 作者:太空狗 更新时间:2023-10-29 17:55:30 24 4
gpt4 key购买 nike

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

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

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)

然后能够将原始构造函数参数与我类(class)的一些额外内容混合使用。像这样:

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

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

编辑:我应该提一下上面的内容是行不通的。错误是: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 中获取它们。

dict.pop() method从字典中删除键,如果存在,则返回关联值,如果缺少,则返回我们指定的默认值。这意味着我们verbose 传递给父类(super class)。如果您只想检查参数是否已设置而不删除它,请使用 kwargs.get('verbose', True)

关于python - 如何将所有参数从 __init__ 传递给父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com