类型提示中的 Self 类型

版本新特性 / Python 3.11

from typing import TypeVar

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


# *** 以前 ***
# 返回“自身”的方法过去用绑定到该类的 TypeVar 标注,
# 这个 TypeVar 要单独声明,并在每个这样的签名中重复
class ShapeOld:
    def __init__(self, width: int = 1) -> None:
        self.width = width

    def wider(self: T, add: int) -> T:
        self.width += add
        return self


class BoxOld(ShapeOld):
    def label(self) -> str:
        return "box " + str(self.width)


print(BoxOld().wider(2).label())


# *** 在 3.11 版本中 ***
from typing import Self


class Shape:
    def __init__(self, width: int = 1) -> None:
        self.width = width

    def wider(self, add: int) -> Self:      # “此对象本身的类型”
        self.width += add
        return self

    @classmethod
    def unit(cls) -> Self:                  # 对构造函数也适用
        return cls()


class Box(Shape):
    def label(self) -> str:
        return "box " + str(self.width)


# 类型检查器知道 Box.wider 返回的是 Box,所以允许使用 .label
print(Box.unit().wider(2).label())

# 类型提示只在基类中写一次,对每个子类都成立