以下代码无法按预期工作。显然,我不能在类定义中使用类自己的类型:
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'))
Run Code Online (Sandbox Code Playgroud)
运行结果如下:
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
Run Code Online (Sandbox Code Playgroud)
此外,检查代码mypy返回:
class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype …Run Code Online (Sandbox Code Playgroud)