函数标注
通过Python 3的PEP 3107引入的,函数参数和返回值都可以使用标注。用 : 类型 的形式指定函数的参数类型,用 -> 类型 的形式指定函数的返回值类型。:和类型之间,->和类型之间有一个半角空格。
例如:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 | #定义未使用标注函数add_no_annotation
def add_no_annotation(x,y):
    return x + y
#定义使用标注函数add_annotation
def add_annotation(x: int, y: int) -> int:
    return x + y
result1 = add_no_annotation(3,5)
result2 = add_annotation(3,5)
print(result1)  # 输出8
print(result2)  # 输出8
 | 
 
然后特别要强调的是,Python并不会因为这些标注而提供额外的校验,没有任何的类型检查工作。也就是说,加了类型标注,也不会对参数和函数返回值进行类型判断。
例如:
| 1
2
3
4
5
6
7
8
 | #定义使用标注函数add_annotation
def add_annotation(x: int, y: int) -> int:
    return x + y
result1 = add_annotation(3,5)
result2 = add_annotation("Hello ","World")  #虽然标注写的是int类型,字符串类型也是可以的
print(result1)  #输出8
print(result2)  #输出Hello World
 | 
 
但这么做的好处是:
让别的程序员看得更明白。让IDE了解类型,从而提供更准确的代码提示、补全和语法检查。
在函数的annotations属性中会有你设定的标注。annotations属性是字典对象。
例如:
| 1
2
3
4
5
6
7
 | #定义使用标注函数add_annotation
def add_annotation(x: int, y: int) -> int:
    return x + y
s = add_annotation.__annotations__
print(type(s))
print(s)
 | 
 
执行以上程序会输出如下结果:
| 1
2
 | <class 'dict'>
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
 | 
 
带有参数默认值的标注函数
我们知道函数参数还可以有默认值,当然,默认值的参数也可以标注。
例如:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
 | #定义使用标注函数add_annotation
def add_annotation(x: int=10, y:int=5) -> int:
    return x + y
print(add_annotation())       # 没有传递参数,使用默认的参数10和5,结果是15
print(add_annotation(15))     # 仅传递了参数x,使用y默认的参数5,结果是20
print(add_annotation(15,20))  # 结果是35
s = add_annotation.__annotations__
print(type(s))
print(s)
 | 
 
执行以上程序会输出如下结果:
| 1
2
3
4
5
 | 15
20
35
<class 'dict'>
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
 | 
 
变量标注
通过Python 3.6的PEP 526,又引入了对变量类型进行标注的方法,包括类变量和实例变量。用 : 类型 的形式指定变量的类型。:和类型之间有一个半角空格。
例如:
| 1
2
 | a: int = 123       # 声明初始值是123,int类型的变量a
b: str = 'hello'   # 声明初始值是hello,str类型的变量b
 | 
 
变量标注和初始值可以分别进行。
例如:
| 1
2
3
4
5
6
7
 | a: int       # 声明int类型的变量a
a = 123      # 初始值是123
b: str       # 声明strt类型的变量b
b = 'hello'  # 初始值是'hello'
print(a)     # 输出123
print(b)     # 输出hello
 | 
 
更进一步,如果你需要指明一个全部由整数组成的列表:
例如:
| 1
2
 | from typing import List
l: List[int] = [1, 2, 3]
 | 
 
同函数标注一样,虽然是强制变量类型,在运行时也不会对其进行类型检查判断。需要注意的是,在IDE编辑器中,有标注的变量,最好初始化成和标注声明的类型,要不然编辑器会报错。但是运行起来的话,不受影响。
例如:
| 1
2
3
4
5
6
7
 | a: int       # 声明int类型的变量a
a = 'world'  # 初始值是world
b: str       # 声明strt类型的变量b
b = 'hello'  # 初始值是'hello'
print(a)     # 输出world,不受标注类型int的影响。
print(b)     # 输出hello
 | 
 
在函数的annotations属性中会有你设定的标注。annotations属性是字典对象。
类变量标注和实例变量标注
例如:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 | class Student:
    name: str = "Student"    #实例变量标注
    def __init__(self,age,score):
    self.age = age
    self.score = score
s = Student(20,80.5)
s.weight: float = 50.5
cls = Student.__annotations__
instance =s.__annotations__
print(type(cls))
print(cls)
print(type(instance))
print(instance)
 | 
 
执行以上程序会输出如下结果:
| 1
2
3
4
 | <class 'dict'>
{'name': <class 'str'>}
<class 'dict'>
{'name': <class 'str'>}
 | 
 
转载请注明本网址。