在Python中,如何以智能而优雅的方式将*args和**kwargs与u_init_u_一起使用?
从docu和一些资料中,我了解了有关在Python中,如何以智能而优雅的方式将*args和**kwargs与u_init_u_一起使用?,python,keyword-argument,Python,Keyword Argument,从docu和一些资料中,我了解了有关*args和**kwargs的基本知识。但是我在想如何以一种好的、pythonic的方式将它们与\uuuu init\uuuu一起使用。 我添加了这个伪代码来描述需求\uuuu init\uuuu()的行为应如下所示: 如果参数name应用于设置memeberself.name及其值。其他成员也一样 如果参数为type(self),则外部对象的成员值应复制到自己的成员self. 如果未指定参数,则应使用默认值,或者(对我来说更好)引发错误 在其他语言(例如
*args
和**kwargs
的基本知识。但是我在想如何以一种好的、pythonic的方式将它们与\uuuu init\uuuu
一起使用。
我添加了这个伪代码来描述需求<代码>\uuuu init\uuuu()的行为应如下所示:
- 如果参数
应用于设置memebername
及其值。其他成员也一样self.name
- 如果参数为
,则外部对象的成员值应复制到自己的成员type(self)
self.
- 如果未指定参数,则应使用默认值,或者(对我来说更好)引发错误
#!/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和pytho3之间的解决方案是否不同。因此,如果有差异,请让我知道。我将把标签改为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?