簡體   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