[英]How to type hint a return an instance of a subclass from a list of superclass in Python
If I have a class that stores a list of superclasses, and I have a method that filters out a specific subclass types, how can I set the type hint to say that the method returns a list of the subclass?如果我有一个存储超类列表的 class,并且我有一个方法可以过滤掉特定的子类类型,我如何设置类型提示以表明该方法返回一个子类列表?
Example:例子:
from typing import List
class Color:
name: str
def __init__(self, name):
self.name = name
class Green(Color):
def __init__(self):
super().__init__('green')
def do_a_green(self):
pass
class Blue(Color):
def __init__(self):
super().__init__('blue')
def do_a_blue(self):
pass
class ColorList:
_color_list: List[Color]
def get_blue_colors(self) -> List[Blue]:
return [color for color in self._color_list
if color.name == 'blue'] # <- error: List comprehension has
# incompatible type List[Color]; expected List[Blue]
The best you can do is probably with a TypeGuard.你能做的最好的可能就是使用 TypeGuard。
from typing import List
from typing_extensions import TypeGuard
class Color:
name: str
def __init__(self, name):
self.name = name
class Green(Color):
def __init__(self):
super().__init__('green')
def do_a_green(self):
pass
class Blue(Color):
def __init__(self):
super().__init__('blue')
def do_a_blue(self):
pass
def _is_blue(color: Color) -> TypeGuard[Blue]:
return color.name == "blue"
class ColorList:
_color_list: List[Color]
def get_blue_colors(self) -> List[Blue]:
return [color for color in self._color_list
if _is_blue(color)]
Or use cast:或者使用强制转换:
def get_blue_colors(self) -> List[Blue]:
return cast(List[Blue], [color for color in self._color_list
if color.name == "blue"])
Edit :编辑:
Or use isinstance
:或者使用
isinstance
:
def get_blue_colors(self) -> List[Blue]:
return [color for color in self._color_list
if isinstance(color, Blue)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.