在Python中是否有PHP的extract的等效功能?
我在找一个和这个功能相似的Python写法。
4 个回答
4
不需要。你为什么需要这个呢?
你可以做以下操作(见评论)
def __api_call__(self, method, resource, **kwargs):
print(kwargs)
def do_call(my_dict):
self.__api_call__('POST', '/api/foobar/', **your_dict) # double asterisk!
10
也许你可以更清楚地说明一下你想做什么。直接回答你的问题可能不太符合Python的风格,因为几乎肯定有更好的方法来实现你的目标。
编辑(根据你的评论):
确实,有更好的方法。
你想做的事情叫做 解包参数列表
,可以这样做:
self.__api_call__('POST', '/api/foobar/', **mydict)
这是一个有效的例子:
>>> def a_plus_b(a,b):
... return a+b
...
>>> mydict = {'a':3,'b':4}
>>> a_plus_b(**mydict)
7
而且它也可以和关键字参数一起使用,正如你所期待的那样:
>>> def a_plus_b(**kwargs):
... return kwargs['a'] + kwargs['b']
...
>>> a_plus_b(**mydict)
7
2
一般来说,人们会使用 locals()
来实现这个效果,但具体的功能还是要看你怎么用。
>>> print apple
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'apple' is not defined
>>> print banana
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'banana' is not defined
>>> variables = {"apple" : "a rigid, juicy fruit", "banana" : "a soft, fleshy fruit"}
>>> for variable,value in variables.iteritems():
... locals()[variable] = value
...
>>> print apple
a rigid, juicy fruit
>>> print banana
a soft, fleshy fruit
编辑
感谢所有认真评论这种方法不好的朋友。我完全同意这是一种糟糕的方法,而且应该在实际的回答中提到,以便任何偶然看到这个页面的人都能注意到。(不要低估这一点;我在某个地方看到过这个技巧的代码片段。我能理解在那个特定情况下它是无害的,但我知道我不能因为在某些情况下它不会出错,就去鼓励这种糟糕的方法。)