
1、使用位置实参
若要使函数接受不同类型的实参,则必须将接受任意数量实参的形参放在函数定义的最后。首先,Python匹配位置实参和关键词实参,然后将剩余的实参收集到最后一个形参中。
1 2 3 4 5 6 7 8 9 10 | >>> def person(city, *args):
... print( 'city: ' + city + ', other args:' )
... for value in args:
... print(value)
...
>>> person( 'beijing' , 'name' , 'age' , 'tel' )
city: beijing, other args:
name
age
tel
|
2、使用关键字实参
有时需要接受任意数量的实际参数,但是不知道传递给函数的信息是什么样的。在这种情况下,可以将函数写成可以接受任意数量的键值对。一个例子是创建用户介绍:知道会收到关于用户的信息,但是你不确定会是什么样的信息。
1 2 3 4 5 6 7 8 9 10 | >>> def person(city, *args):
... print( 'city: ' + city + ', other args:' )
... for value in args:
... print(value)
...
>>> person( 'beijing' , 'name' , 'age' , 'tel' )
city: beijing, other args:
name
age
tel
|
以上就是python在函数中传递实参的方法,希望对大家有所帮助。更多Python学习指路:python基础教程