可以将可变数量的参数传递给函数吗?
- 2024-12-02 08:41:00
- admin 原创
- 170
问题描述:
与在 C 或 C++ 中使用 varargs 类似:
fn(a, b)
fn(a, b, c, d, ...)
解决方案 1:
是的。您可以将其用作非关键字*args
参数。然后,您将能够传递任意数量的参数。
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)
如您所见,Python 将把参数解包为包含所有参数的单个元组。
对于关键字参数,您需要将其作为单独的实际参数接受,如Skurmedel 的回答所示。
解决方案 2:
添加到解除帖子:
您也可以发送多个键值参数。
def myfunc(**kwargs):
# kwargs is a dictionary.
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc(abc=123, efh=456)
# abc = 123
# efh = 456
你也可以将两者混合起来:
def myfunc2(*args, **kwargs):
for a in args:
print a
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123
它们必须按该顺序声明和调用,即函数签名需要为 args、*kwargs,并按该顺序调用。
解决方案 3:
如果可以的话,Skurmedel 的代码适用于 python 2;要使其适应 python 3,请更改iteritems
为items
并在 中添加括号print
。这可以防止像我这样的初学者遇到:AttributeError: 'dict' object has no attribute 'iteritems'
并在其他地方搜索(例如,尝试使用 NetworkX 的 write_shp() 时出现错误“'dict' 对象没有属性 'iteritems'”)为什么会发生这种情况。
def myfunc(**kwargs):
for k,v in kwargs.items():
print("%s = %s" % (k, v))
myfunc(abc=123, efh=456)
# abc = 123
# efh = 456
和:
def myfunc2(*args, **kwargs):
for a in args:
print(a)
for k,v in kwargs.items():
print("%s = %s" % (k, v))
myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123
解决方案 4:
添加到其他优秀帖子中。
有时您不想指定参数的数量,而想使用它们的键(如果在字典中传递的一个参数未在方法中使用,编译器会抱怨)。
def manyArgs1(args):
print args.a, args.b #note args.c is not used here
def manyArgs2(args):
print args.c #note args.b and .c are not used here
class Args: pass
args = Args()
args.a = 1
args.b = 2
args.c = 3
manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3
然后你可以做类似的事情
myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
fun(args)
解决方案 5:
def f(dic):
if 'a' in dic:
print dic['a'],
pass
else: print 'None',
if 'b' in dic:
print dic['b'],
pass
else: print 'None',
if 'c' in dic:
print dic['c'],
pass
else: print 'None',
print
pass
f({})
f({'a':20,
'c':30})
f({'a':20,
'c':30,
'b':'red'})
____________
上述代码将输出
None None None
20 None 30
20 red 30
这与通过字典传递变量参数一样好
解决方案 6:
除了已经提到的好答案之外,另一种解决方法取决于你可以通过位置传递可选的命名参数。例如,
def f(x,y=None):
print(x)
if y is not None:
print(y)
收益
In [11]: f(1,2)
1
2
In [12]: f(1)
1
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD