本节主要内容:
python_func/ target=_blank class=infotextkey>python函数的冗余参数
函数-冗余参数
- 向函数传 元组 - *tupleName
def functionName(arg1, arg2) :
print arg1, arg2
tupleName = (1, 2)
functionName(*tupleName)
- 向函数传 字典 - **dictName
def functionName(arg1, arg2) :
print arg1, arg2
dictName = {"arg1":"value1", "arg2":"value2"}
functionName(**dictName) # 传value
functionName(*dictName) # 传key
- 处理多余参数
- functionName(*args)
- functionName(**keywordargs)
1. 引入
2. 格式化输出
3. 用 元组的元素 给 每个 形参 赋值
3.1 error
3.2 正确
------------------------
def f(arg1, arg2) :
print arg1, arg2
print "%s, %s" % (arg1, arg2)
t = (1, 2)
f(*t)
-------output----------
1 2
1, 2
4. 用 字典的元素 给 每个 形参 赋值
------------------------
def f(arg1, arg2) :
print arg1, arg2
d = {"arg2":"value2" , "arg1":"value1"}
f(*d)
f(**d)
-------output----------
arg1 arg2
value1 value2
5. 处理多余实参
5.1 以 元组 处理 冗余参数
------------------------
def f(x, *args) :
print "x =", x
print "args =", args
f(1)
f(1,2)
f(1,2,3)
-------output----------
x = 1
args = ()
x = 1
args = (2,)
x = 1
args = (2, 3)
5.2 以 元组+字典 处理 冗余参数
------------------------
def f(x, *args, **kwargs) :
print "x =", x
print "args =", args
print "kwargs =", kwargs
f(1)
f(1, 2)
f(1, 2, z = 3)
# f(x = 1, 2, z = 3) # error
f(x = 1, y = 2, z = 3)
-------output----------
x = 1
args = ()
kwargs = {}
x = 1
args = (2,)
kwargs = {}
x = 1
args = (2,)
kwargs = {'z': 3}
x = 1
args = ()
kwargs = {'y': 2, 'z': 3}