3

假设MembershipClass已经创建了一个抽象基类。多个类派生自抽象基类,例如 ,FirstClassSecondClass

我希望在一个函数中使用类型注释,该函数接受任何从MembershipClass. 如果有少量派生类(比如 2),这应该有效:

from typing import Union
def MyFunc(membership_obj: Union[FirstClass, SecondClass]) -> None:
   ...

有没有办法创建一个类型提示,membership_obj它本质上说它的类型是任何派生的类,MembershipClass而不必在类型注释中指定每个可能的派生类?

我已经看到了两种可能的解决方案:

  1. 类型变量
from typing import TypeVar
BaseType = TypeVar('BaseType', bound=MembershipClass)
def MyFunc(membership_obj: BaseType) -> None:
   ...

  1. 直接使用ABC
def MyFunc(membership_obj: MembershipClass) -> None:
   ...

这两种方法都可以接受吗?

4

1 回答 1

1

看起来这两种解决方案都可以工作,尽管 mypy 消息略有不同。考虑以下示例(我已内联添加 mypy 错误):

from abc import ABC
from typing import TypeVar


class Base(ABC):
    pass


class Sub(Base):
    pass


BaseType = TypeVar("BaseType", bound=Base)


def MyFunc(c: Base) -> None:
    pass


def MyFunc2(c: BaseType) -> None:
    pass


if __name__ == "__main__":
    b = Base()
    s = Sub()

    MyFunc(b)
    MyFunc(s)
    MyFunc(3)  # main.py:30: error: Argument 1 to "MyFunc" has incompatible type "int"; expected "Base"

    MyFunc2(b)
    MyFunc2(s)
    MyFunc2(3) # main.py:34: error: Value of type variable "BaseType" of "MyFunc2" cannot be "int"

话虽如此,我认为第二种方法更具可读性和直观性。我认为这TypeVar更适合泛型(这并不是说如果你想你就不应该使用它)。

于 2021-05-03T23:01:15.170 回答