如何遍历函数参数
我有一个Python函数,它接受几个字符串参数,像这样:def foo(a, b, c):
,然后把这些字符串连接在一起。我想要遍历所有的函数参数,检查它们是否不是None(也就是没有值)。请问怎么做呢?有没有简单的方法可以把None转换成空字符串""?
谢谢。
5 个回答
4
你可以使用inspect模块,并定义一个这样的函数:
import inspect
def f(a,b,c):
argspec=inspect.getargvalues(inspect.currentframe())
return argspec
f(1,2,3)
ArgInfo(args=['a', 'b', 'c'], varargs=None, keywords=None, locals={'a': 1, 'c': 3, 'b': 2})
在argspec里有你需要的所有信息,可以用来处理传入的参数。
要连接字符串,只需要使用接收到的参数信息就可以了:
def f(a,b,c):
argspec=inspect.getargvalues(inspect.currentframe())
return ''.join(argspec.locals[arg] for arg in argspec.args)
供参考:
http://docs.python.org/library/inspect.html#inspect.getargvalues
21
def func(*args):
' '.join(i if i is not None else '' for i in args)
如果你要把一些东西连接起来,但其中有的东西是空字符串,你可以用这段代码:''.join(i for i in args if i is not None)
。这段代码的意思是,把所有不为空的东西连接在一起,中间不加任何东西。
69
locals()
这个函数在你函数的开头调用时可能会很有帮助。
示例 1:
>>> def fun(a, b, c):
... d = locals()
... e = d
... print e
... print locals()
...
>>> fun(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}}
示例 2:
>>> def nones(a, b, c, d):
... arguments = locals()
... print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None)
...
>>> nones("Something", None, 'N', False)
The following arguments are not None: a, c, d
回答:
>>> def foo(a, b, c):
... return ''.join(v for v in locals().values() if v is not None)
...
>>> foo('Cleese', 'Palin', None)
'CleesePalin'
更新:
‘示例 1’ 提到,如果你的参数顺序很重要,我们可能需要额外处理一下,因为 locals()
(或者 vars()
)返回的 dict
是无序的。此外,上面的函数在处理数字时也不是很优雅。所以这里有几个改进的建议:
>>> def foo(a, b, c):
... arguments = locals()
... return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None)
...
>>> foo(None, 'Antioch', 3)
'Antioch3'