如何键入将在 Python 中子类化的参数

How to type an argument which will be subclassed in Python

我有一块遵循这样的模式

from typing import Any


class Base:
    ...


class Derived1(Base):
    ...


class Derived2(Base):
    ...


class BasicApp:
    # how to type d in this base class?
    def handle(self, d: Base) -> None:
        print("handle from BasicApp", d)


class AppX(BasicApp):
    def handle(self, d: Derived1) -> None:
        print("handle from AppX", d)


class AppY(BasicApp):
    def handle(self, d: Derived2) -> None:
        print("handle from AppY", d)

我不确定在 BasicApp.d 中输入 d 的正确方法是什么。

我试过d: Base,然后

error: Argument 1 of "handle" is incompatible with supertype "BasicApp"; supertype defines the argument type as "Base"

我尝试了 T = TypeVar('T', bound=Base)d: T,然后

error: Argument 1 of "handle" is incompatible with supertype "BasicApp"; supertype defines the argument type as "T"

正确的方法是什么?

您需要使 BaseApp 通用,以便该方法的参数类型实际上是 class 本身的“函数”。

from typing import Generic, TypeVar


class Base:
    ...


class Derived1(Base):
    ...


class Derived2(Base):
    ...


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


class BasicApp(Generic[T]):
    # how to type d in this base class?
    def handle(self, d: T) -> None:
        print("handle from BasicApp", d)


class AppX(BasicApp[Derived1]):
    def handle(self, d: Derived1) -> None:
        print("handle from AppX", d)


class AppY(BasicApp[Derived2]):
    def handle(self, d: Derived2) -> None:
        print("handle from AppY", d)