1.变量注解
1 2 3 4 5 6 7 8 9 10 11
| a: int = 1 b: float = 1.5 c: str = 'jack' print(a, b, c)
d: list = [0] e: dict = {0:0} f: set = {2,1,1} g: frozenset = {1,3,2} h: tuple = (1,2,3) print(d, e, f, g, h)
|
2.函数注解
注解不会做任何处理,只是存储在函数的 annotations 属性(一个字典)中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| from typing import Optional, Union, NoReturn, Callable, Any, Literal
def square(num: int) -> int: return num ** 2
def func(name: str) -> None: print(name)
def func(name: str) -> NoReturn: raise RuntimeError('error')
def func(name: str) -> Optional[str]: if name: return name
def func(name: str) -> Union[str, int]: if name: return name else: return 0
def func(myfunc: Callable) -> Any: myfunc('Hello') func(print)
Operator = Literal['+', '-', '*', '/'] def func(operator: Operator) -> None: print(operator) func('%') func('+')
|
3.容器注解
1 2 3 4 5 6 7 8 9 10
| from typing import List, Dict, Tuple, Sequence
def func(names: List[str], ages: Dict[str, int]) -> Tuple[str, int]: return ('jack', 20)
def max_age(ages: Sequence[int]): return max(ages) print(max_age([18,28,38]))
|
4.类型别名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| from typing import Tuple, NewType
Point = Tuple[int, int, int]
def func(point: Point): print(point)
func(point=(2, 3, 4))
NewPoint = NewType('NewPoint', Tuple[int, int, int])
def new_func(point: NewPoint): print(point)
new_func(point=(2, 3, 4)) new_func(point=NewPoint((2, 3, 4)))
|
5.类注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| from typing import Optional, Protocol
class Node(): def __init__(self, parent:Optional['Node']=None): self.parent = parent
node: Node = Node()
class Proto(Protocol): def func(self): pass
class A(): def func(self): pass
class B(): pass
a: Proto = A() b: Proto = B()
|
6.泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| from typing import TypeVar
T = TypeVar('T', str, int)
def func(a: T, b: T) -> T: return a + b
func(1, 2) func('1', '2')
from typing import TypeVar, List
TL = TypeVar('TL')
def func(l: List[TL], value: TL) -> None: l.append(value)
l = [1, 2, 3] func(l, 1) func(l, 'a')
|