两分钟掌握Python3.5中类型提示的使用方法

类型提示(Type Hinting)是Python 3.5版本引入的一种语法,它允许开发者为变量、函数参数和返回值指定预期的类型,以方便代码的阅读、维护和检查。类型提示并不会强制Python解释器进行类型检查,也不会影响代码的运行,它只是一种可选的编码规范。

要使用类型提示,你需要遵循以下几个步骤:

# 变量声明
name: str = "Alice"
age: int = 18
scores: list[float] = [95.5, 88.0, 92.0]

# 函数定义
def add(x: int, y: int) -> int:
    return x + y

# 类定义
class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
def add(x: int, y: int) -> int:
    return x + y

print(add(1, 2)) # 正确
print(add("a", "b")) # 错误

运行结果为:

$ mypy test.py
test.py:5: error: Argument 1 to "add" has incompatible type "str"; expected "int"
test.py:5: error: Argument 2 to "add" has incompatible type "str"; expected "int"
Found 2 errors in 1 file (checked 1 source file)

可以看到,mypy工具能够发现传入错误类型的参数,并给出相应的错误信息。

展开阅读全文

页面更新:2024-03-03

标签:提示   类型   变量   使用方法   函数   定义   声明   错误   参数   代码   工具

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top