以下代码无法按预期工作。显然,我不能在类定义中使用类自己的类型:
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 和 for 都有效mypy
?