09 类型别名:更强的语义

类型别名:更强的语义

更强的语义

​ 除了自定义的类型,对基础类型可以进行别名,以形成一种更强的语义:

案例1

NameType = str

class Person:
def __init__(
self,
name: NameType
):
self.name = name

a = Person("Bob")

案例2

from typing import Optional

ReturnType = tuple[int, Option[str]]

def f(a) -> ReturnType:
if a > 0:
print(a)
return 0, None
else:
return 1, "Input is <= 0"

retcode, errmsg = f(0)

相同类型的别名可以兼容

​ 如果对同一个类型起了两个不同的别名,它们可以互相兼容。

UserId = int
OtherUserId = int

id1: UserId = 1
id2: OtherUserId = id1