Python中的类型检查

自由坦荡的智能 2025-04-23 22:28:36

Python 是一种解释型、交互式和面向对象的编程语言。它支持动态类型,具有非常高级的动态数据类型。动态数据类型使得开发者能够专注于实际程序,而不是在编写代码时花费时间和精力去指定数据类型。Python 解释器在运行时会识别数据赋值,并为变量分配必要的数据类型。

示例:

从 datetime 导入 datetimeclass 知道你的年龄:“了解您的年龄段 “”current_date = Nonedef __init__(self) -> None:“从 datetime 初始化当前日期 “”self.current_date = datetime.today()def get_your_age(self, birth_year)-> int:“Get your age ”age = self.current_date.year — birth_year返回年龄def get_day_of_your_birth_date(self, birth_date)-> str:“获取你的出生日期的星期”birth_week_day = ‘’week_day = birth_date.weekday()match str(week_day):case ‘0’: birth_week_day = ‘Monday’case ‘1’: birth_week_day = ‘Tuesday’case ‘2’: birth_week_day = ‘周三’case ‘3’: birth_week_day = ‘周四’case ‘4’: birth_week_day = ‘周五’case ‘5’: birth_week_day = ‘周六’case ‘6’: birth_week_day = ‘星期日’case _: pass返回出生周几如果 __name__ == ‘__main__’:know_ur_age_instance = KnowYourAge()打印(‘出生年份:’,know_ur_age_instance.current_date,'\n 年龄:’,know_ur_age_instance.get_your_age(know_ur_age_instance.current_date.year-10))birth_date_as_input = know_ur_age_instance.current_date # datetime(2023,8,20)print(‘出生日期:’,str(birth_date_as_input.date()),‘\n 工作日:’,know_ur_age_instance.get_day_of_your_birth_date(birth_date_as_input))

当在终端运行 mypy get_your_age.py 时,

遇到以下错误

get_your_age.py:13: 错误:项“None”的“datetime | None”没有属性“year”[联合属性]

get_your_age.py:35: 错误:项“None”的“datetime | None”没有属性“year”[联合属性]

get_your_age.py:39: 错误:项“None”的“datetime | None”没有属性“date”[联合属性]

这些错误表明即使在 Python 程序运行成功并产生结果的情况下,类型指定也是必不可少的,因此,在声明和使用期间,一些类型安全变量可以解决这个问题。

示例

from datetime import datetimeclass 知道你的年龄:“知道你的年龄类”current_date: datetimedef __init__(self) -> None:“初始化当前日期”self.current_date = datetime.today()def get_your_age(self, birth_year: int)-> int:“Get your age ”age: int = self.current_date.year — birth_yearreturn agedef get_day_of_your_birth_date(self, birth_date: datetime) -> str:获取你的出生日期的日期birth_week_day: str = ‘’week_day: int = birth_date.weekday()match str(week_day):case ‘0’: birth_week_day = ‘Monday’case ‘1’: birth_week_day = ‘Tuesday’case ‘2’: birth_week_day = ‘Wednesday’case ‘3’:出生周天 = ‘星期四’case ‘4’:出生周天 = ‘星期五’case ‘5’:出生周天 = ‘星期六’case ‘6’:出生周天 = ‘星期日’case _: pass返回出生周几如果 __name__ == ‘__main__’:know_ur_age_instance = KnowYourAge()打印('出生年份:', know_ur_age_instance.current_date,'\n 年龄:', know_ur_age_instance.get_your_age(know_ur_age_instance.current_date.year-10))birth_date_as_input: datetime = know_ur_age_instance.current_date # datetime(2023,8,20)print(‘ Birth date: ‘, str(birth_date_as_input.date()),‘\n Week day: ‘,know_ur_age_instance.get_day_of_your_birth_date(birth_date_as_input))

一旦完成必要的代码更改并运行 mypy 命令,我们应该能够看到如下输出

成功:在1个源文件中未发现任何问题

类似地,还可以使用其他编译时代码检查选项,例如使用 pylint 来验证程序中的错误并进行修复。pylint 和 mypy 的检查在某些情况下可能会有所不同。

0 阅读:0

自由坦荡的智能

简介:感谢大家的关注