参考:函数参数

Note

A.关键字参数:

1.关键字参数:**kw

可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。

2.支持只传入必选参数;也可以传入任意数目的可选参数,如下例。

eg.

#!/usr/bin/env python3def my_func(name, age, **kw) :print('name:', name, 'age:', age, 'else:', kw)

test

>>> from function3 import my_func>>> my_func('Chen', 20)
name: Chen age: 20 else: {}>>> my_func('Chen', 20, prof='Student')
name: Chen age: 20 else: {'prof': 'Student'}>>> my_func('Chen', 20, prof='Student', city='FuZhou')
name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}

3.关键字参数的作用:”试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,利用关键字参数来定义这个函数就能满足注册的需求。“

4.当然,也可以选择在传入参数的时候直接传入一个dict的内容。这里容易出错,我就翻车了。

eg.

>>> dic = {'prof' : 'Student', 'city' : 'FuZhou'}
>>> my_func('Chen', 20, dic['prof'], dic['city'])
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: my_func() takes 2 positional arguments but 4 were given>>> my_func('Chen', 20, dic)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: my_func() takes 2 positional arguments but 3 were given

第一句错误的原因,是因为传入dic['prof']相当于传入'Student',即一个字符串,这很明显与函数定义的参数不符;第二句同上,只不过由传入字符串变成了传入一个dict。

正确的方法应该是value_name=dict[key]

eg.

>>> my_func('Chen', 20, prof=dic['prof'])
name: Chen age: 20 else: {'prof': 'Student'}>>> my_func('Chen', 20, prof=dic['prof'], city=dic['city'])
name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}

5.如果想直接传入dict,方法也很简单,加上两个星号*

刚才的错误:

>>> my_func('Chen', 20, dic)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: my_func() takes 2 positional arguments but 3 were given

修正:

>>> my_func('Chen', 20, **dic)
name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}

**dic表示把dic这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是dic的一份拷贝,对kw的改动不会影响到函数外的dic。

B.命名关键字参数

1.定义了关键字参数的函数允许用户传入多个关键字key-value值,如果我们想要在函数里面查看一个key是否在传入的dict中,可以通过if···in···的方法查看。

eg.

#!/usr/bin/env python3def my_func(name, age, **kw) :if 'prof' in kw :            # Hint: 'prof' => ''print('prof in')if 'city' in kw :print('city in')print('name:', name, 'age:', age, 'else:', kw)

output

>>> from function3 import my_func
>>> dic = {'prof' : 'Student', 'city' : 'FuZhou'}
>>> my_func('Chen', 20, **dic)
prof in
city in
name: Chen age: 20 else: {'city': 'FuZhou', 'prof': 'Student'}
>>> 

2.如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和prof作为关键字参数。

方法:

my_func(name, age, *, prof, city)

*作为分隔符,指定传入的关键字参数key必须是prof和city。

使用命名关键字参数时,要特别注意,如果没有可变参数,就必须加一个*作为特殊分隔符。如果缺少*,Python解释器将无法识别位置参数和命名关键字参数。

eg.

def my_func2(name, age, *, prof, city) :print(name, age, prof, city)

output

>>> from function3 import my_func2
>>> my_func2('Chen', 20, prof='Student', city='FuZhou')
Chen 20 Student FuZhou

注意:指定了关键字参数的key之后,传入的关键字参数数目必须匹配,并且必须是 key=value 的形式。

命名关键字参数必须传入参数名。

eg.

>>> my_func2('Chen', 20, prof='Student')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: my_func2() missing 1 required keyword-only argument: 'city'>>> my_func2('Chen', 20)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: my_func2() missing 2 required keyword-only arguments: 'prof' and 'city'
>>> my_func2('Chen', 20, 'Student', 'FuZhou')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: my_func2() takes 2 positional arguments but 4 were given

3.命名关键字支持默认参数,在调用时,可以不传入默认参数的值。

C.参数组合

在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数(*[···] or *list_name)、命名关键字参数和关键字参数(**{···} or **dict_name)。

eg.

def my_func3(a, b, c=0, *d, **e) :print(a, b, c, d, e)

output

>>> my_func3('Chen', 20)
Chen 20 0 () {}>>> my_func3('Chen', 20, 100)
Chen 20 100 () {}>>> my_func3('Chen', 20, 100, *['Li', 'Wang'], **{'Li' : 'num1', 'Wang' : 'num2'})
Chen 20 100 ('Li', 'Wang') {'Wang': 'num2', 'Li': 'num1'}>>> 

在函数调用的时候,Python解释器自动按照参数位置和参数名把对应的参数传进去。

也就出现了原文传入一个tuple和一个dict,解释器也正常输出的情况:

>>> t1 = ('Li', 100, 99, 'Wang')>>> d1 = {'Wang' : 'num2', 'Li' : 'num1'}>>> my_func3(*t1, **d1)
Li 100 99 ('Wang',) {'Wang': 'num2', 'Li': 'num1'}>>> t2 = ('Li', 100, 'Wang')>>> my_func3(*t2, **d1)
Li 100 Wang () {'Wang': 'num2', 'Li': 'num1'}        # 按位置解释>>> t3 = ['Li', 100, 'Wang']>>> my_func3(*t3, **d1)
Li 100 Wang () {'Wang': 'num2', 'Li': 'num1'}        # 传入一个list和一个tuple也可以>>> 

2017/1/31

转载于:https://www.cnblogs.com/qq952693358/p/6359044.html

Python学习札记(十三) Function3 函数参数二相关推荐

  1. Python学习总结18:函数 参数篇

    1. 判断函数是否可调用 >>> import math >>> x = 1 >>> y = math.sqrt >>> cal ...

  2. Python学习之路:函数参数及调用

    return:结束函数并返回值 没有return时:返回None 返回值数=1时:返回具体值 返回值是数字+字符串+列表等:返回一个元组 需要return是需要函数完整调用 def test1():p ...

  3. Python学习札记(十一) Function2 函数定义

    参考:定义函数 Note: 先看一段代码实例(Barefoot topo.py): def read_topo():nb_hosts = 0nb_switches = 0links = []with ...

  4. Python学习(14)--内置函数

    Python学习(14)--内置函数 1.Python内置函数 在Python中有很多的内置函数供我们调用,熟练的使用这些内置函数可以让编写代码时事半功倍,所谓内置函数就是那些Python已经预定义并 ...

  5. python学习[第十三篇] 条件和循环

    python学习[第十三篇] 条件和循环 if语句 单一if 语句 if语句有三个部分构成,关键字if本身,判断结果真假的条件表达式,以及表达式为真或非0是执行的代码 if expression: e ...

  6. python学习笔记(14)参数对应

    python学习笔记(14)参数对应 原链:http://www.cnblogs.com/vamei/archive/2012/07/08/2581264.html 笔记: 1 #第14讲 2 #参数 ...

  7. Python学习笔记11:函数修饰符

    Python学习笔记11:函数修饰符 Python有很多有趣的特性,其中函数修饰符就是一个. 我们在之前的那个web应用示例中用过如下写法: @web.route('/log') @符号后边的,就是一 ...

  8. python学习总结----内置函数及数据持久化

    python学习总结----内置函数及数据持久化 抽象基类(了解)- 说明:- 抽象基类就是为了统一接口而存在的- 它不能进行实例化- 继承自抽象类的子类必须实现抽象基类的抽象方法 - 示例:from ...

  9. Python学习札记(六)

    本次学习笔记都是根据<简明Python教程>所做 函数 关键字:def 全局变量:global #fileName func_global.py #关键字 global 声明是全局变量de ...

最新文章

  1. 卧槽!华为大佬整理的Linux学习笔记和资料不小心流落到了外网.……
  2. js更改html元素颜色,HTML - 使用JS根据值更改文本的颜色
  3. SVM中的线性分类器
  4. 字段中存在空值的问题测试
  5. java订单编号生产代码,java 订单编号 生成器,可用于生产环境
  6. Android Studio开发第二篇创建新项目
  7. 如何恢复Linux下被误删除的文件以及如何防止文件被删除
  8. .config 和 kconfig以及 makefile的关系
  9. .NET下使用DataAdapter保存数据时,如何生成command语句及使用事务
  10. SMS短信通API下行接口参数
  11. 【英语学习】【WOTD】bathetic 释义/词源/示例
  12. wxt_hillwill的知识脉络
  13. Docker代理设置方法
  14. 微服务Eureka使用详解
  15. go 服务器压力测试,Go的单元测试与压力测试
  16. EXE文件结构及读取方法 1
  17. 论文解读:6mA-Pred: identifying DNA N6-methyladenine sites based on deep learning
  18. 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题
  19. 什么样的学生最坑导师?
  20. 双重否定的翻译 百度翻译 VS. 谷歌翻译

热门文章

  1. 装逼的翻译,害死多少人,你同意吗?到底什么是非终止状态,终止状态
  2. C#格式化字符串净化代码的方法
  3. apt-clone:备份已安装的软件包并在新的 Ubuntu 系统上恢复它们
  4. 19.C++-(=)赋值操作符、初步编写智能指针
  5. 前端测试利器--Browser-Sync启动命令
  6. java的自动类型转换和强制类型转换
  7. Linux 终端下 dstat 监控工具
  8. Java内存模型FAQ(四)重排序意味着什么?
  9. C语言打包解包文件程序(简易版)
  10. linux 每日学一点《明明白白配置lilo启动引导器》