每天进步一点点-类型注解

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:SunXiuWen
# datetime:2021/12/27 0027
"""
常用类型提示
int,long,float: 整型,长整形,浮点型;
bool,str: 布尔型,字符串类型;
List, Tuple, Dict, Set:列表,元组,字典, 集合;
Iterable,Iterator:可迭代类型,迭代器类型;
Generator:生成器类型

待解决:*_ 是什么意思??????

博客:https://www.cnblogs.com/poloyy/p/15153883.html
"""
# TODO  变量声明
like: str = "happy"


# TODO 函数声明
def test(name: str, age: int = 20) -> str:
    return name + str(age)


# 自定义类型
class MyLog:
    def __init__(self, name):
        self.name = name


def logs(logger: MyLog) -> str:
    return logger.name


logs(MyLog("happy"))

# TODO  内置容器类型
from typing import List, Tuple, Dict, Set

a: List[int] = [1, 23]  # 指定容器里每个元素类型都为int,容器List和Set只能指定一个类型,不然报错
# a1:List[int,str,dict] = [1,"1",dict(name=1)]  #  TypeError: Too many parameters for typing.List; actual 3, expected 1
b: Tuple[str, ...] = ("a", "b")  # 对所有元素生效,加3个逗号
# b1: Tuple[int] = (1, 2)  # 声明和元素个数不统一,会警告,但不报错
b2: Tuple[int, str] = (2, "3")
b3: Tuple[int, str, str] = ("1", "2", "3", "4")
c: Dict[str, int] = {"key": 15000, "age": 30}  # 指定键是str,值为int
d: Set[int] = {1, 2}
# d1: Set[int,str] = {1,"2"} #  TypeError: Too many parameters for typing.List; actual 3, expected 1


# TODO  类型别名解决复杂的嵌套类型
# var: List[float] = [1.0, 1.2]
# 下面通过别名的方式等价写法
This = List[float]
var: This = [1.0, 1.2]

Conn = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Conn, Address]


def web(flag: bool, server: Server) -> str:
    if flag:
        print(server)
        return str(server)
    return "fail"


# TODO  函数默认参数,可变参数
def python_function(flag: bool = True, *args: str, **kwargs: int) -> None:
    """要求可变参数都为字符串,默认参数默认为真,可变关键字参数的值为int"""
    pass


python_function(True, 1, "2", key=1, key1="2")

# TODO  泛型,即支持任意类型
from typing import TypeVar

A = TypeVar(name="A")  # 可以是任意类型

a0: A = 1
a1: A = "1"
a2: A = (1,)

B = TypeVar("B", int, str)  # 可以是整形,也可以是字符串,其他类型就报警
b0: B = 1
b1: B = "1"
b2: B = (1,)  # 不是指定的类型,警告


def b_test(m: B, n: B) -> None:
    pass


b_test(1, 1)
b_test("1", "1")
b_test(1, "1")  # 处于函数声明,多参数类型需一致,才不会警告

# TODO 联合类型Union,可以为指定的范围内的任意类型
from typing import Union

C = Union[int, str]
C_like = [int or str]
c0: C = (1,)
c1: C = 1
c2: C = "1"


def c_test(x: C, y: C) -> None:
    pass


c_test(1, 1)
c_test("1", "2")
c_test(1, "1")  # 处于函数声明,不要求多参数类型相同

# TODO 可选类型Optional,其实就是Union[x,None]的简写,即可以为x类型,也可以为None,只能指定一个类型
# 用这个来进行类型注解时主要解决函数参数传与不传时的情况
from typing import Optional

D = Optional[float]  # 表示可以为浮点型,也可以为空
d0: D = 2.2
d1: D = "1"


def d_test(z: D = None) -> None:
    print(z)


d_test()
d_test("1")  # 如果传参就需要是float或int

# TODO 任意类型Any,任何没有指定类型和返回值的函数,都隐式的指定了类型Any,默认Any类型与每种类型兼容
from typing import Any


def e_t(q): pass


def e_tt(q: Any) -> Any: pass


# TODO 可调用对象 Callable[[x],y], x为可调用函数的参数类型
from typing import Callable


def exec_func(i: str, m: int) -> str:
    print(i, m)
    return i


def fn(f: Callable[[str, int], str], name: str, args=15000) -> str:
    return f(name, args)


fn(exec_func, "china")

#
from typing import NewType

n = NewType("n", int)
s = n(3)
print(s)
print(n("ha"))

# TODO dataclass 数据类,对类进行装饰,给类添加魔法方法,如__init__,repr等

from dataclasses import dataclass, field
from dataclasses import field


class User(object):
    id: int
    name: str
    friends: List[int] = field(default_factory=list)


#
#
data = {'id': 123, 'name': 'china'}
user = User(**data)
print(user.id, user.name, user.friends)

posted @ 2023-03-16 14:19  Alive_2020  阅读(25)  评论(0编辑  收藏  举报