函数注释
Python 的函数注释功能使您能够添加有关函数定义中声明的参数以及 return 数据类型的其他解释性元数据。Python 解释器在执行函数时不会考虑它们。它们主要用于 Python IDE,用于为程序员提供详细的文档。
尽管您可以使用 Python 的文档字符串功能来记录函数,但如果对函数的原型进行某些更改,它可能已过时。因此,由于 PEP 3107,注释功能是在 Python 中引入的。
注释是添加到参数或返回数据类型的任何有效 Python 表达式。注释的最简单示例是指定参数的数据类型。Annotation 在参数前面加上冒号后作为表达式提及。
例请记住,Python 是一种动态类型语言,不会在运行时强制执行任何类型检查。因此,在调用函数时,使用数据类型注释参数没有任何影响。即使给出了非整数参数,Python 也不会检测到任何错误。
def myfunction(a: int, b: int):
c = a+b
return c
print (myfunction(10,20))
print (myfunction("Hello ", "Python"))
它将产生以下输出 -
Hello Python
返回类型的函数注释
注释在运行时被忽略,但对 IDE 和静态类型检查器库(如 mypy)很有帮助。
您也可以为 return 数据类型提供 annotation。在括号后面和冒号之前,放置一个箭头 (->),后跟注释。
例在此示例中,我们为 return type 提供 annotation。
def myfunction(a: int, b: int) -> int:
c = a+b
return c
print(myfunction(56,88))
print(myfunction.__annotations__)
这将生成以下输出 -
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
带表达式的函数注释
由于在运行时会忽略使用数据类型作为注释,因此您可以放置任何充当参数元数据的表达式。因此,function 可以有任何任意表达式作为 Annotation。
例在下面的示例中,我们使用 expression 作为函数注释。
def total(x : 'marks in Physics', y: 'marks in chemistry'):
return x+y
print(total(86, 88))
print(total.__annotations__)
以下是输出 -
{'x': 'marks in Physics', 'y': 'marks in chemistry'}
具有默认参数的函数注释
如果要指定 default 参数和注释,则需要将其放在 annotation 表达式之后。默认参数必须位于参数列表中的 required 参数之后。
示例 1以下示例演示如何为函数的默认参数提供注释。
def myfunction(a: "physics", b:"Maths" = 20) -> int:
c = a+b
return c
print (myfunction(10))
Python 中的函数也是一个对象,其属性之一是 __annotations__。您可以使用 dir() 函数进行检查。
print (dir(myfunction))
这将打印包含 __annotations__ 作为属性之一的 myfunction 对象列表。
示例 2
__annotations__ 属性本身是一个字典,其中参数是键,其值的表示法是。
def myfunction(a: "physics", b:"Maths" = 20) -> int:
c = a+b
return c
print (myfunction.__annotations__)
它将产生以下输出 -
示例 3
函数可以有任意位置和/或任意关键字参数。也可以为它们提供注释。
def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
pass
print (myfunction.__annotations__)
它将产生以下输出 -
示例 4
如果您需要为函数参数提供多个 annotation 表达式,请在参数本身前面以 dictionary 对象的形式提供它。
def division(num: dict(type=float, msg='numerator'), den: dict(type=float, msg='denominator')) -> float:
return num/den
print (division.__annotations__)
它将产生以下输出 -