簡體   English   中英

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] 類型?

您可以使用類型斷言/轉換來覆蓋推斷的類型:

from typing import cast

As = cast(List[A], [...])

基本上由你來確保你的類型是你聲明的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM