当前分类:python>>正文

Python类型注释:提高代码清晰度和可维护性

来源:互联网   更新时间:2023年8月10日  

Python 笔记

一、类型注释的基础知识

def sum_of_two_numbers(a: int, b: int) -> int:
    return a + b

二、类型检查工具

def sum_of_two_numbers(a: int, b: int) -> int:
    return a + b

sum_of_two_numbers("hello", "world")
example.py:4: error: Argument 1 to "sum_of_two_numbers" has incompatible type "str"; expected "int"
example.py:4: error: Argument 2 to "sum_of_two_numbers" has incompatible type "str"; expected "int"

三、Python类型的常见注释

def concatenate_strings(str_1: str, str_2: str) -> str:
    return str_1 + str_2

四、类型变量和泛型注释

from typing import TypeVar, List

T = TypeVar('T')

def first_element(lst: List[T]) -> T:
    return lst[0]

五、结论

本文固定链接:https://6yhj.com/leku-p-5298.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 电商