我知道* 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 :(得分:3)
参数位于本地命名空间dict中,因此请使用它:
def foo(self, arg1, arg2, arg3):
my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".
format(**locals())
答案 1 :(得分: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
的函数,则不会显示该参数。
答案 2 :(得分: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