[英]How to use *args and **kwargs with __init__ in a smart and elegant way in Python?
From docu and from some tutorials I know the basics about *args
and **kwargs
. 从docu和一些教程中,我了解有关
*args
和**kwargs
的基础知识。 But I think about how to use them with __init__
in a nice and pythonic way. 但是我考虑如何以一种不错的Python方式将它们与
__init__
一起使用。 I added this pseudo code to describe the needs. 我添加了此伪代码来描述需求。
__init__()
should behave like this: __init__()
行为应如下所示:
name
it should be used to set the memeber self.name
with its value. name
,则应使用其值来设置成员self.name
。 The same for each other member, too. type(self)
then the member values of the foreign object should be duplicated into the own members self.*
type(self)
,则应将异物的成员值复制到自己的成员self.*
In other languages (eg C++) I just would overload the constructor. 在其他语言(例如C ++)中,我只会重载构造函数。 But now with Python I don't know how to implement this in one function.
但是现在使用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()
I am not sure if the solution would be different between Python2 and 3. So if there is a difference please let me know. 我不确定Python2和3之间的解决方案是否会有所不同。因此,如果有区别,请告诉我。 I will change the tag to Python3.
我将标记更改为Python3。
You could just describe what you wrote in text. 您可以只描述您在文本中写的内容。 That is,
那是,
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?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.