Python3中typing模块

Python类型注解是Python 3.5版本之后引入的新特性,它可以让开发者在函数、变量等声明时为其指定类型。typing模型能够声明类型,防止运行时出现参数和返回值类型不符合的问题。

### 1. 基本类型注解
def hello(name: str) -> str:
    return ('Hello, ' + name)
    
print(hello("张三"))

### typing包 ###
### 2. 复合类型
from typing import List, Tuple, Dict
 
my_list = List[Tuple[str, int]] 
my_dict = Dict[str, str]
  
my_list= [('a',1),('b',2)]
print(my_list)

my_dict = {'name':"aa","addr":"xxx"}
print(my_dict)

### 3. 类型别名
from typing import List

# ector和List[float]将被视为可互换的同义词
Vector = List[float]

vec = [1,2,3]
print(type(Vector))
print(List[float])
print(type(vec))

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]
 
# a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector) # [2.0, -8.4, 10.8]


### 3. 创建不同的类型
from typing import NewType,Tuple
UserInfo = NewType('UserInfo', Tuple[str,int])
user1 = UserInfo(("张三",20))
print(type(user1))
print(user1)
 
### 4. Any类型
a: Any = None
a = [] # OK
a = 2 # OK
 
s: str = ""
s = a # OK
print(s) # 2

#Optional:可选类型
#Callable:可调用类型
#Literal:字面类型

### 5. 用户定义的泛型类型
from typing import TypeVar, Generic
from logging import Logger
T = TypeVar('T')
class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value
    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new
    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value
    def log(self, message: str) -> None:
        self.logger.info('%s: %s', self.name, message)

参考:

https://www.bookstack.cn/read/python-3.10.0-zh/e133648b02fa6d6d.md

你可能感兴趣的:(python)