1

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

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我应该为类方法使用哪些注释?仅将其标记为-> 'Foo'不会捕获在派生类(如Bar. 所以print调用中的表达式不会知道它是 aBar和 has lines。我如何表达结果将是参数的一个实例cls

4

1 回答 1

1

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

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())
于 2020-06-18T17:50:46.900 回答