【python】给函数传递任意数量的实参

1.在预先不知道有多少个实参的情况下。可以使用如下操作,允许函数从调用语句中收集任意数量的实参。

def function_name(*test):
    print(test)

function_name('1')
function_name('1','2','3')

 输出结果:

('1',)
('1', '2', '3')

形参*test让python 创建一个名为test的空元组,并将收到的所有值都封装到这个元组中。

2.如果要让函数接收不同类型的实参,必须在函数定义中,将接收任意数量实参的形参放在形参的最后。

def function_name(size,*tests):
    print("\n"+str(size))
    for test in tests:
        print(test+' ')
function_name(12,'1')
function_name(12,'1','2','3')

3.使用任意数量的关键字实参,预先不知道传递给函数的会是什么信息。

示例代码如下

def function_name(first,last,**user_info):
    profile={}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile['key'] = value
    return profile

user_profile = function_name('albert','einstein',location = 'princeton',field = 'physics')
print(user_profile)

输出结果:

{'first_name': 'albert', 'last_name': 'einstein', 'key': 'physics'}

我们调用函数function_name(),向它传递名'albert'和姓'einstein',还有两个键值对(location=‘princeton’和field='physics'),并将返回的profile存储到user_profile中。

猜你喜欢

转载自blog.csdn.net/zl1107604962/article/details/90477179