1.接受任意长度形参,组成turple
def function(*args):
# type(args)==turple
# args==(1, 2, 3, 4)
print(args)
ant=0
for i in range(len(args)):
ant+=args[i]
return ant
print(function(1,2,3,4)) # 10
2.接受任意长度形参,组成dict
def function(**args):
# type(args)==<class'dict'>
print(type(args))
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(args)
ants = 0
for key in args:
ants+=args[key]
return ants
print(function(a=1,b=2,c=3,d=4)) # 10
# 注意这种方法是错误的
print( function({"a":1,"b":2,"c":3,"d":4}) )
# TypeError: function() takes 0 positional arguments but 1 was given
def my_function(**kwargs):
# {'a': 1, 'b': 2}
print(kwargs)
my_dict = {'a': 1, 'b': 2}
my_function(**my_dict)
3. 拿出参数
在list中
def sample_function(a, b, c):
print(a, b, c)
list = [1, 2, 3]
sample_function(*list)
list2=[10,list,20]
list3=[10,*list,20]
# [10, [1, 2, 3], 20]
print(list2)
# [10, 1, 2, 3, 20]
print(list3)
在turple中
def sample_function(a, b, c):
print(a, b, c)
list = (1, 2, 3)
sample_function(*list)
list2=(10,list,20)
list3=(10,*list,20)
# (10, (1, 2, 3), 20)
print(list2)
# (10, 1, 2, 3, 20)
print(list3)
4.函数传参对号入座
def test(a, b):
print(f"a={a}, b={b}")
d = {'b': 200, 'a':30}
test(**d)
参数和形参名称不对应,报错
def test(c,d):
print(c," ",d)
d = {'b': 100, 'a':10}
test(**d)
"""
File "d:\WorkSpace\MachineLearning\d2l_learn\mainTest2.py", line 4, in <module>
test(**d)
TypeError: test() got an unexpected keyword argument 'b'
"""
题外话:看到*args和**kwds既不害怕了
class Person(object):
def __init__(self) -> None:
pass
def __call__(self, *args: Any, **kwds: Any) -> Any:
pass
def __new__(cls) :
pass