首页 > 解决方案 > 如何键入检查引用类的数据类函数?

问题描述

我开始在 Python 中进行类型检查,并且遇到了我的第一个问题。我有这样的功能

import datetime

from dataclasses import dataclass

@dataclass
class example_object:
    date: datetime.date

    def __lt__(self, other):
        return self.date < other.date

A = example_object(datetime.date(2020, 4, 5))
B = example_object(datetime.date(2020, 4, 4))

print(A<B, B<A)

这按预期工作,但我想对lt方法进行类型检查。我试着这样做:

    def __lt__(self, other: example_object) -> bool:
        return self.date < other.date

但这不起作用,当我尝试运行脚本时,我得到:

Traceback (most recent call last):
  File "type_example2.py", line 6, in <module>
    class example_object:
  File "type_example2.py", line 9, in example_object
    def __lt__(self, other: example_object) -> bool:
NameError: name 'example_object' is not defined

我做错了吗?如何使用我正在定义的类键入检查此函数?

标签: pythontype-hintingtypecheckingpython-typingpython-dataclasses

解决方案


推荐阅读