如何使用Python类型注释返回self?

时间:2017-06-10 22:25:35

标签: python python-3.x mypy

我有一个带有setter的课程,如下所示:

class FooBuilder(object):
    bar: int = 0
    baz: int = 0

    def set_bar(self, bar: int) -> FooBuilder:
        self.bar = bar
        return self

    def set_baz(self, baz: int) -> FooBuilder:
        self.baz = baz
        return self

我希望类返回自己,因为我喜欢方法链接:

def return_foo_builder_with_set_vars() -> FooBuilder:
    return FooBuilder().set_bar(1).set_baz(2)

上面的代码用mypy检查。但是当我运行python3时,我收到错误:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    class FooBuilder(object):
  File "test.py", line 5, in FooBuilder
    def set_bar(self, bar: int) -> FooBuilder:
NameError: name 'FooBuilder' is not defined

据推测,在类声明完成之前,FooBuilder没有在运行时中定义。那么输入这个的正确方法是什么?

0 个答案:

没有答案