Python 类型提示 - 提示过滤列表了解类型
Python Type Hinting - hint a filtered list understand the type
我在列表中有两个 类 个实例:
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
我如何暗示 As 是 List[A] 类型?
您可以使用 type assertion/cast 覆盖推断类型:
from typing import cast
As = cast(List[A], [...])
基本上由您来确保您的类型与您声明的类型一致。
我在列表中有两个 类 个实例:
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
我如何暗示 As 是 List[A] 类型?
您可以使用 type assertion/cast 覆盖推断类型:
from typing import cast
As = cast(List[A], [...])
基本上由您来确保您的类型与您声明的类型一致。