类型化python:在类定义中使用类自己的类型 [英] typed python: using the classes' own type inside class definition
问题描述
以下代码未按预期工作.显然,我不能在类定义中使用类自己的类型:
The following code does not work as expected. Apparently, I cannot use the classes' own type inside class definition:
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
检查代码返回:
Also, checking the code with mypy
returns:
class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype "object"
如何更正此代码以使其对 Python 和 mypy
均有效?
How can I correct this code to be valid, both for Python and for mypy
?
推荐答案
名称 Foo
尚未绑定,因为在您尝试使用时尚未定义该类本身名称(请记住:函数参数在函数定义时计算,而不是在函数调用时).
The name Foo
isn't bound yet, because the class itself has not yet been defined at the time that you try to use the name (remember: function arguments are evaluated at function definition time, not at function call time).
从 Python 3.7+ 开始,您可以通过添加以下内容推迟对注释的评估在模块顶部导入:
From Python 3.7+ you can postpone evaluation of annotations by adding this import at the top of the module:
from __future__ import annotations
在 Python 3.10 中,延迟评估将成为默认行为.对于 Python <3.7、可以使用字符串字面量来延迟类型的求值:
In Python 3.10 postponed evaluation will become the default behavior. For 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'))
这篇关于类型化python:在类定义中使用类自己的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!