Python 父 class 函数的类型提示 returns 与调用 class 的类型相同?

Python Type Hint for parent class function that returns same type as calling class?

有没有一种方法可以键入提示父 class 函数以表明它 returns 与实际调用 class 的类型相同?

考虑一下:

'''

import __future__

class A:
    def func_a(self) -> "A":
        return self
class B(A):
    def func_b(self) -> None:
        print("func_b was called")
a = A()
a.func_a()
b = B()
b2 = b.func_a()
b2.func_a()
# IDE doesn't recognize that b2 is of class B and so b2.func_b() is white not yellow
# but still works
b2.func_b()

'''

func_b() 是白色而不是黄色:

您可以使用 Self 来自 typing:

from typing import Self

class A:
    def func_a(self) -> Self:
        return self

您可以在此处找到更多详细信息:https://www.python.org/dev/peps/pep-0673/