以下代码没有按预期工作。显然,我不能在类定义中使用类自己的类型:
class Foo:
def __init__(self, key :str) -> None:
self.key = key
def __eq__(self, other :Foo) -> bool:
return self.key == other.key
print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))
运行结果为:
Traceback (most recent call last):
File "class_own_type.py", line 1, in <module>
class Foo:
File "class_own_type.py", line 5, in Foo
def __eq__(self, other :Foo) -> bool:
NameError: name 'Foo' is not defined
此外,使用
mypy
返回检查代码:
class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype "object"
如何更正此代码以使其对 Python 和
mypy
都有效?
当定义
Foo.__eq__
时,名称Foo
仍然是未绑定的,因为类本身还没有被创建。请记住:函数参数是在函数定义时计算的,而不是在函数调用时。
从 Python 3.7+ 开始,您可以 通过在模块顶部添加此导入来推迟对注释的评估:
from __future__ import annotations
对于 Python < 3.7, you can use string literals to delay evaluation of the type:
class Foo:
def __init__(self, key: str) -> None:
self.key = key
def __eq__(self, other: 'Foo') -> bool:
return self.key == other.key
print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))