【python】给函数参数和返回值标注类型

目录

(1)类型标注进化历史

从Python 3.0开始的类型标注

从Python 3.5开始的类型标注库 typing

(2)更细化的类型标注

1.返回一个列表,且列表的元素类型是指定的

2.返回字典类型,键和值都是指定类型

3.返回自定义类型


(1)类型标注进化历史

从Python 3.0开始的类型标注

Python 3.0开始,Python 已经支持基础的类型标注,例如,你可以在函数声明中这样写:

def func(a: int, b: str) -> bool:
    return b.isdigit() and a > int(b)

这里的int, str, bool都是类型标注,他们说明了函数参数和返回值的类型。

从Python 3.5开始的类型标注库 typing

从 Python 3.5开始,Python 增加了一个新的模块,叫做typing。这个模块定义了很多用于类型标注的类和函数,包括一些容器类型,例如List, Dict, Tuple等。

from typing import List, Dict 


def func(a: List[int], b: Dict[str, int]) -> bool: 
    p1 = all(isinstance(x, int) for x in a)
    p2 = all(isinstance(k, str) and isinstance(v, int) for k, v in b.items())
    ret = p1 and p2 
    return ret

这里的List[int]和Dict[str, int]是类型标注,他们分别表示一个整数列表和一个以字符串为键,整数为值的字典。

(2)更细化的类型标注

1.返回一个列表,且列表的元素类型是指定的

如果你想要指定一个函数返回一个列表,且列表的元素具有特定类型,你可以使用类型提示来实现。以下是一个简单的例子:

from typing import List

def create_list_of_integers(length: int) -> List[int]:
    result = [i for i in range(length)]
    return result

# 调用函数
my_list = create_list_of_integers(5)
print(my_list)

在这个例子中,create_list_of_integers 函数接受一个整数参数 length,并返回一个包含整数的列表。通过在函数声明中使用 -> List[int],我们明确了返回的是整数类型的列表。

如果你的函数返回的列表包含不同类型的元素,你可以使用 Union 类型来表示这个混合类型的列表。例如:

from typing import List, Union

def create_mixed_list(length: int) -> List[Union[int, str]]:
    result = [i if i % 2 == 0 else str(i) for i in range(length)]
    return result

# 调用函数
mixed_list = create_mixed_list(5)
print(mixed_list)

在这个例子中,create_mixed_list 函数返回一个包含整数和字符串的列表。使用 Union[int, str] 来表示列表的元素类型可以容纳这两种不同的数据类型。

2.返回字典类型,键和值都是指定类型

如果你想要指定一个函数返回一个字典,且字典的键和值都具有特定的类型,你可以使用类型提示。以下是一个例子:

from typing import Dict

def create_dict_of_integers(length: int) -> Dict[int, int]:
    result = {i: i * 2 for i in range(length)}
    return result

# 调用函数
my_dict = create_dict_of_integers(5)
print(my_dict)

在这个例子中,create_dict_of_integers 函数接受一个整数参数 length,并返回一个字典,其中键和值都是整数类型。通过在函数声明中使用 -> Dict[int, int],我们明确了返回的字典的键和值的类型。

如果你的函数返回的字典包含不同类型的键和值,你可以使用 Dict 和 Union 类型。例如:

from typing import Dict, Union

def create_mixed_dict(length: int) -> Dict[Union[int, str], Union[int, str]]:
    result = {i: str(i) if i % 2 == 0 else i for i in range(length)}
    return result

# 调用函数
mixed_dict = create_mixed_dict(5)
print(mixed_dict)

在这个例子中,create_mixed_dict 函数返回一个包含整数和字符串的字典,使用 Dict[Union[int, str], Union[int, str]] 来表示字典的键和值的混合类型。

3.返回自定义类型

像下面这样,自定义了一个DataInfo类,函数get_data_info()指定返回一个列表,且列表的元素类型必须为DataInfo。

from typing import List, Dict


class DataInfo(object):
    def __init__(self):
        self.name = "tom"
        self.age = 18
        self.value_list = []
        self.test_ret = 0.3789
        self.income_dict = dict()


def get_data_info() -> List[DataInfo]:
    m = DataInfo()
    x = [m]
    return x


ret = get_data_info()
print(ret[0].test_ret)

end

相关推荐

  1. python函数参数返回标注类型

    2024-05-01 21:40:04       11 阅读
  2. Python函数进阶:作为参数传递、作为返回

    2024-05-01 21:40:04       35 阅读
  3. 数学函数参数返回探秘

    2024-05-01 21:40:04       32 阅读
  4. 数组作为参数返回

    2024-05-01 21:40:04       7 阅读
  5. C/C++__VA_ARGS__学习--自动打印函数参数返回

    2024-05-01 21:40:04       15 阅读
  6. python 函数-02-返回&注释格式

    2024-05-01 21:40:04       23 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-01 21:40:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-01 21:40:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-01 21:40:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-01 21:40:04       18 阅读

热门阅读

  1. 日拱一卒,月进一步(10)

    2024-05-01 21:40:04       11 阅读
  2. PostgreSQL数据类型总结

    2024-05-01 21:40:04       7 阅读
  3. vue项目快速构建

    2024-05-01 21:40:04       8 阅读
  4. Unity编辑器扩展

    2024-05-01 21:40:04       8 阅读
  5. Postgresql从小白到高手 十:Linux服务器配置详解

    2024-05-01 21:40:04       10 阅读
  6. SQL中distinct的用法

    2024-05-01 21:40:04       8 阅读
  7. 情商测试的新浪潮:如何准确评估个人情商?

    2024-05-01 21:40:04       10 阅读
  8. SGP.31-10

    2024-05-01 21:40:04       8 阅读
  9. ES基础查询,term级参数介绍

    2024-05-01 21:40:04       10 阅读
  10. DOM事件

    DOM事件

    2024-05-01 21:40:04      10 阅读
  11. 为什么MySQL使用B+树而不是跳表

    2024-05-01 21:40:04       8 阅读
  12. Ansible playbook之变量引用

    2024-05-01 21:40:04       10 阅读
  13. 聊聊服务器散热方案的演进

    2024-05-01 21:40:04       10 阅读