这个应该很简单。假设我有一个函数,我从函数中的某个包中调用了一些函数。我想自定义函数包的传递参数,以确定用户是否已将参数传递给我的函数。示例代码:
import SomePackage as sp
def myFunc(foo, bar, baz=None, xad=False):
# some code to do some stuff...
# then finally:
if baz is not None:
sp.someFunc(data=foo, method=bar, aux=baz)
else:
sp.someFunc(data=foo, method=bar)
有没有办法用一条整齐的Pythonic线替换最后4行?类似的东西:
def myFunc(foo, bar, baz=None, xad=False):
# some code to do some stuff...
# then finally:
sp.someFunc(data=foo, method=bar, [aux=baz if baz is not None])
答案 0 :(得分:2)
您可以使用argument unpacking执行此操作:
def func1(one, two, three):
args = {"one": one, "two": two, "three": three}
func2(*args)
def func2(one, two, three):
print "one = %s, two = %s, three = %s" % (one, two, three)
if __name__ == "__main__":
func1(one="does", two="this", three="work")
示例运行:
python foo.py
one = does, two = this, three = work
当然,您可以在传递之前修改args
。