Python - typing 模块 —— Callable

2022-09-28 08:19:47

前言

typing 是在 python 3.5 才有的模块

前置学习

Python 类型提示:

https://eli-coin.blog.csdn.net/article/details/122301840

常用类型提示:

Python - typing 模块 —— 常用类型提示_eli的博客-CSDN博客

类型别名

https://eli-coin.blog.csdn.net/article/details/122302139

NewType

https://eli-coin.blog.csdn.net/article/details/122302242

Callable

是一个可调用对象类型

查看对象是否可调用

语法

# 返回True或False
isinstance(对象, Callable)

栗子

# 最简单的函数
def print_name(name: str):
    print(name)


# 判断函数是否可调用
print(isinstance(print_name, Callable))

x = 1
print(isinstance(x, Callable))



# 输出结果
True
False

函数是可调用的,所以是 True,而变量不是可调用对象,所以是 False

Callable 作为函数参数

看看 Callable 的源码

Callable type; Callable[[int], str] is a function of (int) -> str.
  • 第一个类型(int)代表参数类型
  • 第二个类型(str)代表返回值类型

栗子

def print_name(name: str):
    print(name)


# Callable 作为函数参数使用,其实只是做一个类型检查的作用,检查传入的参数值 get_func 是否为可调用对象
def get_name(get_func: Callable[[str], None]):
    return get_func


vars = get_name(print_name)
vars("test")


# 等价写法,其实就是将函数作为参数传入
def get_name_test(func):
    return func


vars2 = get_name_test(print_name)
vars2("小菠萝")


# 输出结果
test
小菠萝

Callable 作为函数返回值

# Callable  作为函数返回值使用,其实只是做一个类型检查的作用,看看返回值是否为可调用对象
def get_name_return() -> Callable[[str], None]:
    return print_name


vars = get_name_return()
vars("test")


# 等价写法,相当于直接返回一个函数对象
def get_name_test():
    return print_name


vars2 = get_name_test()
vars2("小菠萝")


# 输出结果
test
小菠萝

TypeVar 泛型

https://eli-coin.blog.csdn.net/article/details/122302445

Any Type

https://eli-coin.blog.csdn.net/article/details/122302480

Union

https://eli-coin.blog.csdn.net/article/details/122302496

Optional

Python - typing 模块 —— Optional_eli的博客-CSDN博客

  • 作者:欧晨eli
  • 原文链接:https://eli-coin.blog.csdn.net/article/details/122302358
    更新时间:2022-09-28 08:19:47