在 class 主体的类型定义中引用 class 名称
Referring to the class name within a type definition in the class body
我在使用相关 class 的输入语句中引用 class 名称时遇到问题。以下代码显示了问题:
class C():
def __init__(self, a: C)
self.a = a
@property
def a(self) -> C:
return self.a
编译器抱怨 C 未定义。我想做的事情是不可能的吗,我是否必须为此放弃使用打字 class?
你可以用这个导入解决它 from __future__ import annotations
PEP-0563:
from __future__ import annotations
class C:
def __init__(self, a: C):
self.a = a
@property
def a(self) -> C:
return self.a
或者简单地使用字符串:
class C:
def __init__(self, a: 'C'):
self.a = a
@property
def a(self) -> 'C':
return self.a
我在使用相关 class 的输入语句中引用 class 名称时遇到问题。以下代码显示了问题:
class C():
def __init__(self, a: C)
self.a = a
@property
def a(self) -> C:
return self.a
编译器抱怨 C 未定义。我想做的事情是不可能的吗,我是否必须为此放弃使用打字 class?
你可以用这个导入解决它 from __future__ import annotations
PEP-0563:
from __future__ import annotations
class C:
def __init__(self, a: C):
self.a = a
@property
def a(self) -> C:
return self.a
或者简单地使用字符串:
class C:
def __init__(self, a: 'C'):
self.a = a
@property
def a(self) -> 'C':
return self.a