带有抽象基类的 Python 类型提示

mri*_*rip 7 python abc type-hinting

我有一个 ABC 方法,子类应该返回他们自己的类型,我正在尝试找出最好的方法来提示这个。例如:

from abc import ABC, abstractmethod

class Base(ABC):
    @abstractmethod
    def f(self): ## here i want a type hint for type(self)
        pass

class Blah(Base):
    def __init__(self, x: int):
        self.x = x

    def f(self) -> "Blah":
        return Blah(self.x + 1)
Run Code Online (Sandbox Code Playgroud)

我能想到的最好的是这个,它有点沉重:

from abc import ABC, abstractmethod
from typing import TypeVar, Generic

SELF = TypeVar["SELF"]

class Base(ABC, Generic[SELF]):

    @abstractmethod
    def f(self) -> SELF:
        pass

class Blah(Base["Blah"]):

    def __init__(self, x: int):
        self.x = x

    def f(self) -> "Blah":
        return Blah(self.x+1)
Run Code Online (Sandbox Code Playgroud)

我有更好/更清洁的方法吗?

小智 1

使用 python 3.7,它通过从以下位置导入注释来工作:__future__

from __future__ import annotations

class Base():
    def f(self) -> Base: ## Here the type is Base since we can not guarantee it is a Blah
        pass

class Blah(Base):
    def __init__(self, x: int):
        self.x = x

    def f(self) -> Blah: ## Here we can be more specific and say that it is a Blah
        return Blah(self.x + 1)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢您的回答。但是,这会迫使您在每个子类中覆盖“f”,即使内容完全相同 (2认同)