我有一个带有方法的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)
有没有更好/更清晰的方法?
cls
类型的实例,请参见 Can you annotate return type when value is instance of cls?。 - Martijn Pieters