繁体   English   中英

Python 类型注释,例如派生自抽象基础 class 的 class 实例

[英]Python type annotations for instance of class derived from abstract base class

假设已创建抽象基础 class MembershipClass 多个类派生自抽象基 class,例如FirstClassSecondClass等。

我希望在 function 中使用类型注释,它接受从MembershipClass派生的任何 class 作为参数。 如果有少量派生类(比如 2),这应该有效:

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

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

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

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

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

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

看起来这两种解决方案都可以工作,尽管 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更适合generics (这并不是说如果你想你就不应该使用它)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM