来自 docu 和一些 tutorials我了解有关 *args
和 **kwargs
的基础知识。但我思考如何以一种很好的 Python 方式将它们与 __init__ 一起使用。
我添加了这个伪代码来描述需求。 __init__()
的行为应如下所示:
- 如果参数
name
应该用于设置成员self.name
及其值。其他成员也一样。 - 如果参数为
type(self)
,则外部对象的成员值应复制到自己的成员self.*
- 如果没有给出参数,则应使用默认值,否则(对我来说更好)会引发错误。
在其他语言(例如 C++)中,我只是重载构造函数。但现在使用 Python,我不知道如何在一个函数中实现这一点。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Foo:
def __init__(self, *args, **kwargs):
# if type() of parameter == type(self)
# duplicate it
# else
# init all members with the parameters
# e.g.
# self.name = name
# explicite use of the members
f = Foo(name='Doe', age=33)
# duplicate the object (but no copy())
v = Foo(f)
# this should raise an error or default values should be used
err = Foo()
我不确定Python2和3之间的解决方案是否会有所不同。因此,如果有差异,请告诉我。我将把标签更改为Python3。
最佳答案
您可以只描述您在文本中所写的内容。也就是说,
def __init__(self, *args, **kwargs):
if len(args) == 1 and not kwargs and isinstance(args[0], type(self)):
other = args[0]
# copy whatever is needed from there, e. g.
self.__dict__ = dict(other.__dict__) # copy it!
else:
self.__dict__ = kwargs
# what do we do with args here?
关于python - 如何在 Python 中以智能且优雅的方式将 *args 和 **kwargs 与 __init__ 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29063580/