使用Python typehints指定“all”类型

2024-04-19 22:48:39 发布

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

如果我在Python中将一个变量注释为能够拥有两种类型中的任何一种,我可以使用typing.Union,如下所示:

How to specify multiple return types using type-hints

但是,如何将变量注释为必须同时拥有两种类型的?你知道吗

用例

这有点做作,因为对于这个小示例,我们可以定义一个TwoCourseMenu类。但是,如果我们有n接口,那么我们真的不想定义n×n组合。你知道吗

我想把Union任何一个)替换成表示所有的东西。你知道吗

from typing import Union

class BasicMeal:
    def main_name( self ):
        return "spam"

class IWithDesert:
    def desert_name( self ):
        raise NotImplementedError()

class TwoCourseSpamMenu( BasicMeal, IWithDesert ):
    def desert_name( self ):
        return "spam"

def present( input: Union[BasicMeal, IWithDesert] ):
    print( f"You're having '{input.main_name()}' followed by '{input.desert_name()}'." )

present( TwoCourseSpamMenu() )

Tags: nameselftyping类型inputreturn定义main