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

时间:2020-07-07 16:15:18

标签: python type-hinting abc

我有一个带有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)

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

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)

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

1 个答案:

答案 0 :(得分:0)

使用 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)