Python:类型提示一个类方法,该方法为继承的类返回该类的实例



考虑以下内容:

from __future__ import annotations
class A:
def __init__(self):
print("A")
self.hello = "hello"
# how do I type this so that the return type is A for A.bobo()
# and B for B.bobo()?
@classmethod
def bobo(cls) -> UnknownType:
return cls()

class B(A):
def __init__(self):
print("B")
super().__init__()
self.world = "world"

instance_of_B = B.bobo()  # prints "B", then "A", and returns an instance of B

我想键入hintbobo类方法,这样mypy就可以知道,在Bbobo方法的情况下,返回的不仅仅是A的实例,而是B的实例。我真的不清楚该怎么做,或者这是否可能。我认为像Type[cls]这样的东西可能会起作用,但我不确定这对mypy来说是否有语法意义。

关于如何应用Brian答案的示例:

  • 带有TypeVar
from typing import TypeVar

AnyA = TypeVar("AnyA", bound="A")

class A:
def __init__(self):
print("A")
self.hello = "hello"
@classmethod
def bobo(cls: type[AnyA]) -> AnyA:
return cls()
class B(A):
def __init__(self):
print("B")
super().__init__()
self.world = "world"
reveal_type(B.bobo())  # B
  • Self
from typing import Self
class A:
def __init__(self):
print("A")
self.hello = "hello"
@classmethod
def bobo(cls) -> Self:
return cls()
class B(A):
def __init__(self):
print("B")
super().__init__()
self.world = "world"
reveal_type(B.bobo())  # B

如果你的Python版本还没有Self,你可以使用打字扩展包,它可以作为一些打字功能的后台端口:

- from typing import Self
+ from typing_extensions import Self

您将不得不使用TypeVar,谢天谢地,在Python 3.11中,typing.Self类型即将出现。本政治公众人物对此进行了详细描述。它还指定了在此之前如何使用TypeVar

最新更新