在Python中,如何以智能而优雅的方式将*args和**kwargs与u_init_u_一起使用?

在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. 如果未指定参数,则应使用默认值,或者(对我来说更好)引发错误 在其他语言(例如

从docu和一些资料中,我了解了有关
*args
**kwargs
的基本知识。但是我在想如何以一种好的、pythonic的方式将它们与
\uuuu init\uuuu
一起使用。 我添加了这个伪代码来描述需求<代码>\uuuu init\uuuu()的行为应如下所示:

  • 如果参数
    name
    应用于设置memeber
    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和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?