Python函数参数和注解的使用

作者:自动化代码美学 时间:2021-09-23 17:34:50 

目录
  • 四种参数

  • 仅限关键字参数

  • 内省中的函数参数

  • 函数注解

四种参数

Python函数func定义如下:


def func(first, *args, second="Hello World", **kwargs):
   print(first)
   print(args)
   print(second)
   print(kwargs)

func("dongfanger", "san", py="good")

运行后会输出:


dongfanger
('san',)
Hello World
{'py': 'good'}

它有四种参数:

  • first是定位参数,positional parameter,不可省略。

  • *args是可变参数,arguments,存入元组。

  • second是默认值参数,default argument values,可以省略。

  • **args是关键字参数,keyword arguments,存入字典。

func函数的调用方式有以下这些:

①传入单个定位参数。


func("dongfanger")

dongfanger
()
Hello World
{}

②第一个参数后的任意个参数会被*args捕获,存入一个元组。


func("dongfanger", "a", "b", "c")

dongfanger
('a', 'b', 'c')
Hello World
{}

③没有明确指定名称的关键字参数会被**kwargs捕获,存入一个字典。


func("dongfanger", j="1", k="2")

dongfanger
()
Hello World
{'j': '1', 'k': '2'}

④second只能作为关键字参数传入。


func("dongfanger", second="cool")

dongfanger
()
cool
{}

⑤定位函数也能作为关键字参数传入。


func(first="san")

san
()
Hello World
{}

⑥字典前加上**,其所有元素作为单个参数传入,同名键会绑定到对应具名参数上,余下的被**args捕获。


my_dict = {"first": "dongfanger", "location": "cd", "second": "cool", "age": "secret"}
func(**my_dict)

dongfanger
()
cool
{'location': 'cd', 'age': 'secret'}

除了这四种参数,还有一种Python3新增加的仅限关键字参数。

仅限关键字参数

仅限关键字参数(keyword-only argument)是Python3的新特性,func函数的second参数就是仅限关键字参数,“仅限”的意思是说,只能通过关键字参数指定,它一定不会捕获未命名的定位参数。

假如把参数位置调整一下定义another_func函数:


def another_func(first, another_second="Hello World", *args,  **kwargs):
   print(first)
   print(another_second)
   print(args)
   print(kwargs)

another_func("dongfanger", "a", "b", "c")

输出会变成:


dongfanger
a  # 注意这里
('b', 'c')
{}

another_second不是仅限关键字参数,而只是默认值参数,因为它捕获到了定位参数。

由此得知,定义仅限关键字参数,必须把它放到*args参数后面,就像func函数一样,反例是another_func函数。

还有第二个方法定义仅限关键字参数,在签名中放一个*:


>>> def f(a, *, b):  # b是仅限关键字参数
...    return a, b
...
>>> f(1, b=2)  # 只能传关键字参数
(1, 2)
>>> f(1, 2)  # 不能传定位参数
Traceback (most recent call last):
 File "<input>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1, 2, 3)  # 不能传定位参数
Traceback (most recent call last):
 File "<input>", line 1, in <module>
TypeError: f() takes 1 positional argument but 3 were given

仅限关键字参数不一定要有默认值,就像b一样,强制必须传入实参。

内省中的函数参数

函数内省的意思是说,当你拿到一个“函数对象”的时候,你可以继续知道,它的名字,参数定义等信息。这些信息可以通过函数对象的属性(一些双下划线的魔法方法)得到。

对于func函数:


def func(first, *args, second="Hello World", **kwargs):
   print(first)
   print(second)
   print(args)
   print(kwargs)

和another_func函数:


def another_func(first, another_second="Hello World", *args,  **kwargs):
   print(first)
   print(another_second)
   print(args)
   print(kwargs)

【__defaults__属性】

元组,保存着定位参数和关键字参数的默认值。


print(func.__defaults__)  # None

print(another_func.__defaults__)  # ('Hello World',)

【__kwdefaults__属性】

字典,保存仅限关键字参数。


print(func.__kwdefaults__)  # {'second': 'Hello World'}

print(another_func.__kwdefaults__)  # None

【__code__属性】

code对象引用,code对象自身有很多属性,其中包括参数名称。


print(func.__code__.co_varnames)  # ('first', 'second', 'args', 'kwargs')

print(another_func.__code__.co_varnames)  # ('first', 'another_second', 'args', 'kwargs')

另外还可以使用inspect库的signature方法来查看内省中的函数参数:


from inspect import signature

print(signature(func))  
# (first, *args, second='Hello World', **kwargs)

框架和IDE等工具可以使用这些信息验证代码。

函数注解

如果刷过力扣算法题,那么对函数注解就不会陌生。比如:


def clip(text:str, max_len:'int > 0'=80) -> str:
   pass

参数:后面是注解表达式,可以用来注解参数类型和约束。如果参数有默认值,注解放在参数名和=号之间。

可以在函数末尾的)和:之间添加->和注解表达式,来对返回值添加注解。

注解表达式可以是任何类型,最常用的类型是类(如str或int)和字符串(如'int > 0')。

函数注解只是个注解,Python对注解所做的唯一的事情是,把它们存入函数的__annotations__属性中:


print(clip.__annotations__)
#{'text': <class 'str'>, 'max_len': 'int > 0', 'return': <class 'str'>}

Python不做检查,不做强制,不做验证,什么操作都不做!注解只是元数据,可以供框架和IDE等工具使用。

来源:https://www.cnblogs.com/df888/p/14634619.html

标签:python,函数参数,注解
0
投稿

猜你喜欢

  • 13个超酷的js显示时间效果

    2007-08-30 09:52:00
  • ASP教程:自己写的数据库操作类

    2008-11-21 17:29:00
  • ASP+AJAX做类似google的搜索提示

    2008-10-24 13:49:00
  • 解决golang编译提示dial tcp 172.217.160.113:443: connectex: A connection attempt failed(推荐)

    2023-07-16 04:24:49
  • Python+selenium 获取一组元素属性值的实例

    2021-06-06 02:28:27
  • Python实现的简单模板引擎功能示例

    2022-01-24 04:47:36
  • 10条改进你的CSS代码的方法

    2010-03-20 22:07:00
  • python中关于CIFAR10数据集的使用

    2021-04-14 22:08:05
  • python time时间库详解

    2023-10-09 03:20:57
  • Python 模拟购物车的实例讲解

    2021-01-13 05:24:08
  • JavaScript 解析 Cookie 的函数

    2007-11-08 11:58:00
  • 倾斜的鼠标翻转导航制作上的烦恼

    2007-06-20 16:39:00
  • php实现微信公众号主动推送消息

    2023-11-16 15:10:31
  • Python列表排序方法reverse、sort、sorted详解

    2022-01-06 22:16:39
  • python实现多线程的方式及多条命令并发执行

    2023-08-09 11:37:20
  • Python3中exp()函数用法分析

    2023-06-11 03:17:24
  • 通过表单的做为二进制文件上传request.totalbytes提取出上传的二级制数据

    2011-03-16 10:39:00
  • 简介Python中用于处理字符串的center()方法

    2021-04-15 20:47:17
  • 如何用变量实现群聊和悄悄话?

    2010-05-19 21:33:00
  • PHP实现基于3DES算法加密解密字符串示例

    2023-08-15 18:48:35
  • asp之家 网络编程 m.aspxhome.com