python - 如何在 Python 中以智能且优雅的方式将 *args 和 **kwargs 与 __init__ 一起使用?

标签 python keyword-argument

来自 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/

相关文章:

python - 如何使用 Spacy 将 Rasa Bot 部署到 Heroku

python - 通过 Python 中的正则表达式从列表中删除元素

python - 根据 git 中的提交获取文件的年龄

ruby - Ruby 中的关键字参数解包 (splat)

python - 我可以发送 **kwargs 来代替 requests.post 中的设置参数吗?

python - 理解 '*' "keyword only"python3 函数中的参数表示法

python - 从多处理 Python 中的 multiprocessing.Queue() 返回值

python - 适合多类分类的深度学习结构

python - args/kwargs 的特殊用途

python - 在 Python 函数中使用 **kwargs