工厂方法的类型注解

Type annotations for factory method

假设我有一个用作工厂的 class 方法:

class Foo:

  def __init__(self, text):
    self.text = text

  @classmethod
  def from_file(cls, path):
    with open(path, 'rt') as f:
      return cls(f.read())


class Bar(Foo):

  def lines(self):
    return self.text.count('\n')


print(Bar.from_file('bar.txt').lines())

现在我想为此添加pytype注释。我应该为 from_file class 方法使用什么注释?仅仅将其标记为 -> 'Foo' 并不能捕获在派生 class 的情况下已知的更具体的类型,例如 Bar。所以 print 调用中的表达式不知道它是 Bar 并且有 lines。我如何表达结果将是参数 cls?

的一个实例

您可以为此使用类型变量。

from typing import Type, TypeVar


FooType = TypeVar('FooType', bound='Foo')


class Foo:

  text: str

  def __init__(self, text: str):
    self.text = text

  @classmethod
  def from_file(cls: Type[FooType], path: str) -> FooType:
    with open(path, 'rt') as f:
      return cls(f.read())


class Bar(Foo):

  def lines(self) -> int:
    return self.text.count('\n')


print(Bar.from_file('bar.txt').lines())