python中函数传参详解

yipeiwu_com6年前Python基础

一、参数传入规则

可变参数允许传入0个或任意个参数,在函数调用时自动组装成一个tuple;

关键字参数允许传入0个或任意个参数,在函数调用时自动组装成一个dict;

1. 传入可变参数:

 def calc(*numbers):
   sum = 0
   for n in numbers:
     sum = sum + n * n
   return sum

以上定义函数,使用如下:

传入多个参数,

calc(1, 2, 3, 4)
30 #函数返回值

传入一个列表,

nums = [1, 2, 3]
calc(*nums) # 通过 * 将list中的元素作为可变参数传入函数
14 # 函数返回值

2.传入关键字参数:

>>> def person(name, age, **kw):
...   print('name: ', name, 'age: ', age, 'other: ', kw)
... 
>>> 
>>> person('luhc', 24, city='Guangzhou')
name: luhc age: 24 other: {'city': 'Guangzhou'}

同样,可以将预先定义的dict作为参数传入以上函数:

>>> info = {'city': 'Guangzhou', 'job': 'engineer'}
>>> 
>>> person('luhc', 24, **info)
name: luhc age: 24 other: {'city': 'Guangzhou', 'job': 'engineer'}

注意: 函数person 获得的是参数 info 的一份拷贝,在函数内修改不会影响 info 的值

3. 在关键字参数中,可以限制关键字参数的名字:

# 通过 * 分割,以指定关键字参数名
>>> def person(name, age, *, city, job):
...   print('name: ', name, 'age: ', age, 'city: ', city, 'job: ', job)
... 
>>> 
>>> person('luhc', 24, city='Guangzhou', job='engineer')
name: luhc age: 24 city: Guangzhou job: engineer

# 如果传入参数中,存在参数名不在定义的范围内,将抛出异常
>>> person('luhc', 24, city='Guangzhou', jobs='engineer')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: person() got an unexpected keyword argument 'jobs'
>>>

此外,如果函数中已经指定可变参数,则 * 可以省略,如下:

# 省略了用 * 作为分割,指定关键字参数名
>>> def person(name, age, *args, city, job):
...   print('name: ', name, 'age: ', age, 'args: ', args, 'city: ', city, 'job: ', job)  
... 
>>> 
>>> person('luhc', 24, 'a', 'b', city='Guangz', job='engineer')
name: luhc age: 24 args: ('a', 'b') city: Guangz job: engineer
>>> 
# 同样,如果传入了关键字参数未指定的参数名,则抛出异常
>>> person('luhc', 24, 'a', 'b', city='Guangz', job='engineer', test='a')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: person() got an unexpected keyword argument 'test'
>>>

二、参数组合使用:

参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数

def f1(a, b, c=0, *args, **kw):
  print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

def f2(a, b, c=0, *, d, **kw):
  print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

 以上就是本文给大家介绍的全部内容了,希望能够对大家理解Python的函数参数的传递有所帮助

相关文章

跟老齐学Python之dict()的操作方法

dict的很多方法跟list有类似的地方,下面一一道来,并且会跟list做一个对比 嵌套 嵌套在list中也存在,就是元素是list,在dict中,也有类似的样式: >>...

详解python--模拟轮盘抽奖游戏

详解python--模拟轮盘抽奖游戏

题目: 轮盘分为三部分: 一等奖, 二等奖和三等奖; 轮盘转的时候是随机的, 如果范围在[0,0.08)之间,代表一等奖, 如果范围在[0.08,0.3)之间,代表2等奖, 如果范围在[...

基于python及pytorch中乘法的使用详解

numpy中的乘法 A = np.array([[1, 2, 3], [2, 3, 4]]) B = np.array([[1, 0, 1], [2, 1, -1]]) C = np...

Python列表推导式与生成器表达式用法示例

本文实例讲述了Python列表推导式与生成器表达式用法。分享给大家供大家参考,具体如下: 和列表一样,列表推导式也采用方括号[]表示,并且用到了一个简写版的for循环,第一部分是一个生成...

教女朋友学Python(一)运行环境搭建 原创

教女朋友学Python(一)运行环境搭建 原创

下班比较早,吃了饭没什么事,就和女朋友一起研究了Python。 编程语言有很多,为什么选择它呢?因为它火吧,没什么好解释的,下面开始第一步,环境搭建。网上的教程实在太多,各种系统的各种版...