我的问题与标题所暗示的不同(我不知道如何总结这个问题,所以我很难用谷歌搜索)。
我不想要 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 方法。
创建接口(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)
- 你说 - 函数
foo
中的参数d
可以使用两种方法a
和b
。这就是您所需要的。
关于python - 键入多种类型的提示值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57962266/