键入多种类型的提示值?

Type hinting values that are multiple types?

我的问题与标题所暗示的不同(我不知道如何总结这个问题,所以我很难谷歌搜索)。

我不想要 Union 类型。 Union[A, B] 表示类型可以是 A 类型,也可以是 B 类型。

我需要相反。我希望它的意思是它既是 A 类型又是 B 类型,这在 python 中是可能的,因为混入。

也就是说,我需要键入一个函数提示,这样我知道传递的参数将是一个 class,它同时具有 A 和 B 作为 parents,因为我的函数使用来自两个混合。 Union 类型提示允许传递具有 A 而没有 B 的内容,这是不允许的。

示例

from typing import Union

class A(object):
    def a(self):
        return True

class B(object):
    def b(self):
        return True

class C(A, B):
    pass

def foo(d: Union[A,B]) -> bool: #need something other than Union! 
    print(d.a() and d.b())

我需要 d 成为 A 和 B。但目前它允许我发送 A 而不是 B 的东西,并且在它尝试调用 non-existent 函数时出错

>>> foo(A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
AttributeError: 'A' object has no attribute 'b'
>>> foo(B())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
AttributeError: 'B' object has no attribute 'a'
>>> foo(C())
True

另外我想指出,类型不能只是 d: C。这是因为有很多 classes 有 A 和 B,而且需要维护的 Union 长得离谱。

您可以使用下一个 OOP 方法。

  1. 创建接口 - 它是 python 中的抽象 class,它可以显示方法,实现具体的 classes。示例:

    from abc import ABC, abstractmethod
    
    class MyAB(ABC):
        @abstractmethod
        def a(self):
            pass
    
        @abstractmethod
        def b(self):
            pass
    
    
    class A(object):
        def a(self):
            return True
    
    
    class B(object):
        def b(self):
            return True
    
    
    class ConcreteClass(MyAB, A, B):
        pass
    
    
    def foo(d: MyAB):
        print(d.a() and d.b())
    
    
    c = ConcreteClass()
    
    foo(c)
    
  1. 你说 - 函数 foo 中的参数 d 可以使用两种方法 ab。这就是您所需要的。