2015-02-06 52 views
2

我知道在* arg,** kwarg上有很多问题/答案。不过,我做得有点倒退,但没有找到它解决(也许我只是不知道该怎么问这样的问题。)无论如何,我希望能够简化以下:将函数参数作为字典使用

def foo(self, arg1, arg2, arg3): 
    my_dict = dict(arg1=arg1, arg2=arg2, arg3=arg2) 
    my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}". 
       format(**my_dict) 

注,我不会将foo定义为(self,** kwargs),因为我喜欢填充函数的自动完成组件。

感谢,

+0

所以你想从一些参数创建一个字典? – nbro 2015-02-06 17:13:23

+2

可能会使用'** locals()'? – mshsayem 2015-02-06 17:19:07

+0

@mshsayem - 如何写作答案? – tdelaney 2015-02-06 17:31:55

回答

3

的参数是在本地命名空间字典,所以用它:

def foo(self, arg1, arg2, arg3): 
    my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}". 
       format(**locals()) 
+0

像魅力一样工作,谢谢。 – SteveJ 2015-02-06 17:44:46

1

inspect是你在找什么:

import inspect 

class T(object): 
    def foo(self, arg1, arg2, arg3): 
     frame = inspect.currentframe() 
     args, _, _, values = inspect.getargvalues(frame) 
     my_dict = {arg: values[arg] for arg in args if arg != 'self'} 
     my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".format(**my_dict) 
     print my_dict 
     print my_str 

z = T() 
z.foo(3,4,5) 

注意arg != 'self'部分,因为这是一个方法调用。如果您有一个参数为self的功能,则不会显示该参数。

+0

据我所知,你选择inspect vs locals()的原因是什么?我需要注意哪些优势或陷阱? – SteveJ 2015-02-06 17:49:48

+0

@SteveJ不是。唯一的区别是当地人也会存储其他局部变量。也就是说,你必须在函数的开头调用当地人。 – dmg 2015-02-06 18:59:41

0

正如@dmg提到你可以使用inspect

import inspect 

def find_args(f): 
    return inspect.getargspec(f)[0] 

def foo(arg1, arg2, arg3): 
    my_args = find_args(foo) 
    my_dict = { k: v for k,v in zip(my_args, [arg1, arg2, arg3])} 
    my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".format(**my_dict) 
    print my_str 

foo('a','b', 'c') 

将返回

a went up the b hill to fetch a pail of c