Python类型提示一个过滤列表了解该类型

2024-04-16 10:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

列表中有两个类实例:

from typing import List, Union

class A:
  my_type: str = 'A'
class B:
  my_type: str = 'B'

my_list: List[Union[A, B]] = [A(),A(),B(),B()]
As: List[A] = [a for a in my_list if a.my_type == 'A']

def function_that_gets_only_array_of_As(arr: List[A]):
    print(arr)

function_that_gets_only_array_of_As(As) # this yields a type hint error

我该如何提示列表[A]类型的As


Tags: ofonly列表thatmyastypefunction