python - 键入多种类型的提示值?

标签 python python-3.x types type-hinting

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

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

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

也就是说,我需要键入一个函数提示,这样我就知道传递的参数将属于同时具有 A 和 B 作为父类的类,因为我的函数使用来自两个混入的方法。 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 的东西,并且在它尝试调用不存在的函数时出错

>>> 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。这是因为有很多类都有 A 和 B,而且需要维护的 Union 长得可笑。

最佳答案

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

  1. 创建接口(interface) - 它是 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)
    
  1. 你说 - 函数 foo 中的参数 d 可以使用两种方法 ab。这就是您所需要的。

关于python - 键入多种类型的提示值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57962266/

相关文章:

c# - 在编译时为 switch case 生成 const 字符串

java - 原生 Java 类的类型问题

c++ - 函数调用表达式的类型是什么?

python - sqlite (python) 的 MPI 锁定

python - lxml:元素不是该节点的子节点

python - 将列表转换为字典列表

Python单元测试: Ensure that objects do not contain data from previous run

python - 带轴参数的 Tensorflow tf.gather

python - Seaborn 和 pd.scatter_matrix() 绘图颜色问题

python-3.x - 使用 python 从 azure 数据湖解压缩 .gz 文件