输入多种类型的提示值?

Cru*_*her 6 python types type-hinting python-3.x

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

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

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

也就是说,我需要输入提示一个函数,以便我知道传递的参数将属于一个同时具有 A 和 B 作为父项的类,因为我的函数使用来自两个 mixin 的方法。联合类型提示允许传递不应该被允许的有 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())
Run Code Online (Sandbox Code Playgroud)

我需要 d 是 A 和 B。但目前它允许我发送 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())
Run Code Online (Sandbox Code Playgroud)

此外,我想指出的是,类型不能只是d: C. 这是因为有很多类有 A 和 B,这将是一个需要维护的长得可笑的联合。

小智 3

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

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

    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)
    
    Run Code Online (Sandbox Code Playgroud)
  1. 你说 -d函数中的参数foo可以使用两种方法ab。这就是您所需要的。