简体   繁体   English

如何键入提示从 Python 中的超类列表返回子类的实例

[英]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.

相关问题 我如何键入提示Python函数返回从超类派生的任何类的实例? - How do I type-hint that a Python function returns instance of any class derived from a superclass? Python:如何覆盖子类中实例属性的类型提示? - Python: how to override type hint on an instance attribute in a subclass? 输入子类的提示 - Type hint for instance of subclass 如何从超类实例创建子类实例 - How to create a subclass instance from a superclass instance 键入提示列表的子类 - Type hint a subclass of list 如何从超类的实例创建子类的实例? - How do I create an instance of a subclass from an instance of a superclass? 如何使超类查询集返回子类对象? 或者将超类查询集向下转换为子类列表? - How to make superclass querysets return subclass objects? Or downcast the superclass queryset to a subclass list? 子类作为 python 中超类/类型提示列表的输入无效 - Subclass not valid as input to list of Superclass / type hinting in python 如何输入提示Exception的子类的返回值? - How to type hint a return value of Exception's subclass? 如何从 Python 中的现有超类类型 object 实例化子类类型变量 - How to instantiate a subclass type variable from an existing superclass type object in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM