对于将其他派生类的实例列表作为属性包含的类,正确的类型注释方式是什么?
Bellow是一个具有两对基类和派生类的"简单"示例,我可以在其中重现我遇到困难解决的mypy
个错误.
from dataclasses import dataclass
from typing import List, TypeVar
ClassType = TypeVar("ClassType", bound="BaseClass")
@dataclass
class BaseClass:
a: int
b: int
@dataclass
class DerivedClass(BaseClass):
c: str
@dataclass
class BaseExample:
list_attr: List[ClassType] # line 20
def validate(self, attrs: List[ClassType]) -> List[ClassType]:
return [attr for attr in attrs if attr.a > 0]
@dataclass
class DerivedExample:
list_attr: List[ClassType] # Line 28 # Is actually List[DerivedClass]
other_attr: int
def select(self, attrs: List[ClassType]) -> List[ClassType]:
return [attr for attr in attrs if attr.c] # line 32
ex = DerivedExample(list_attr=[DerivedClass(a=1, b=1, c="text")], other_attr=0)
我收到以下典型错误:
example.py:20: error: Type variable "example.ClassType" is unbound
example.py:20: note: (Hint: Use "Generic[ClassType]" or "Protocol[ClassType]" base class to bind "ClassType" inside a class)
example.py:20: note: (Hint: Use "ClassType" in function signature to bind "ClassType" inside a function)
example.py:28: error: Type variable "example.ClassType" is unbound
example.py:28: note: (Hint: Use "Generic[ClassType]" or "Protocol[ClassType]" base class to bind "ClassType" inside a class)
example.py:28: note: (Hint: Use "ClassType" in function signature to bind "ClassType" inside a function)
example.py:32: error: "ClassType" has no attribute "c"
Found 3 errors in 1 file (checked 1 source file)
类型==0.942
Python3.8.6
我在这里错误地使用了TypeVar吗?
我也试着按照答案here中的建议使用Generic
,像BELLOW一样定义BaseClass
,但它没有解决问题.
ClassType = TypeVar("ClassType", bound="BaseClass")
@dataclass
class BaseClass(Generic[ClassType]):
a: int
b: int
我也try 了不使用bound
属性,如建议的in the documentation,但我得到了相同的错误.
有没有不同的方式来接近这个 struct ?