簡體   English   中英

如何從 -> Human | 分配一個動物 | 外星人 | 無作為 Python 3.7.x+ 中 @dataclass 的類型

[英]How can I assign a one from -> Human | Animal | Alien | None as the type with @dataclass in Python 3.7.x+

我將 class 初始化如下

class Filter:
    ...
    # no need to assign types
    def get_type(self, type_name:str):
        if type_name == 'human':
            return Human()
        elif type_name == 'animal':
            return Animal()
        elif type_name == 'alien':
            return Alien()
        return None
    ...

和 Filter.get_type() 在 vscode 中表示類似於(method) get_type: (data: dict) -> Human | Animal | Alien | None (method) get_type: (data: dict) -> Human | Animal | Alien | None (method) get_type: (data: dict) -> Human | Animal | Alien | None (vscode 指示)

但是,我不確定如何將多個可選類型分配給我的變量,例如

import Filter

my_type: ??? = Filter.get_type()

通過將類型添加到my_type ,自動補全將識別 Human、Animal 和 Alien 中的子類和變量(或繞過 None)

如何將列表[Human, Animal, Alien]中的多種類型分配給 my_type?

使用typing.Union

from dataclasses import dataclass
from typing import Union

@dataclass
class Foo:
    bar: Union[int,str,list,tuple]

試試這個,它使用 3.8 中的Literal概念來制作類型“集合”,並使用Optional來指示None何時可能是有效類型(參見https://docs.python.org/3/library/typing.ZFC35FDC78A8D226 ) :


from typing import Literal, Optional

Filter_Types: Literal[Human, Animal, Alien]

class Filter:

    def get_type(self, type_name: str) -> Optional[Filter_Types]:
        ...

暫無
暫無

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

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