Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在Python中使用kwargs添加参数_Python 3.x_Python_Ipython - Fatal编程技术网

Python 3.x 在Python中使用kwargs添加参数

Python 3.x 在Python中使用kwargs添加参数,python-3.x,python,ipython,Python 3.x,Python,Ipython,下面是我的功能 def list_abc(self, name, id, keywords): cmd = ABC() //ABC is a class cmd.id=id cmd.name=name cmd.keywords=keywords return ABC(cmd) 我希望在Python中使用**kwargs传递名称、id和'关键字 你知道怎么做吗 提前感谢。[kwargs.items()中k,v的set

下面是我的功能

def list_abc(self, name, id, keywords):
        cmd = ABC() //ABC is a class
        cmd.id=id
        cmd.name=name
        cmd.keywords=keywords
        return ABC(cmd)
我希望在Python中使用**kwargs传递
名称
id
和'
关键字

你知道怎么做吗


提前感谢。

[kwargs.items()中k,v的setattr(cmd,k,v)]
@DrTyrsa,无需创建新列表。@khachik它未分配给任何变量,因此在下一行中被销毁。这只是循环的一个简短形式。比手工分配属性更快,更不容易出错。@DrTyrsa:我认为如果你调用函数是为了它的副作用,最好是创建一个显式for循环。它更易于阅读,并且避免了为列表分配内存(即使您没有将其分配给任何对象,Python仍然会创建列表,然后将其丢弃)。@ThomasK如果您有一个具有大量属性的类“浪费内存”,那么您肯定是做错了什么。
kwargs = {'name': 'Frank', 'id': 999, 'keywords': ['cool', 'smart']}
result = self.list_abc(**kwargs)
def list_abc(self, **kwargs):
    # check if 'name' in kwargs, etc
    cmd = ABC()
    cmd.id = kwargs['id']
    cmd.name = kwargs['name']
    cmd.keywords = kwargs['keywords']
    return ABC(cmd) # not sure what ABC(ABC) does

...
some_instance.list_abc(name='name', id=1, keywords=['good', 'luck'])


# or, if have a dictionary containing name, id and keywords, you can pass it to the
# method as follows
data = {'name':'name', 'id':1, 'keywords':('a', 'b')}
some_instance.list_abc(**data)