Python 类型注释:任何注释属性的方法?

Ram*_*hum 7 python annotations python-3.x

我正在定义一个 Python 类:

class Foo:
    bar = property(lambda self: Bar(self))
Run Code Online (Sandbox Code Playgroud)

我想注释该bar属性以说明它包含一个 class 项Bar。有没有一种可接受的方式来做到这一点?我知道这是有效的 Python 语法:

bar: Bar = property(lambda self: Bar(self))
Run Code Online (Sandbox Code Playgroud)

但这是一种公认​​的属性注释方式吗?

Jim*_*ard 6

如果您想安全,只需将其重构为使用装饰器形式并指定返回值:

class Foo:
    @property
    def bar(self) -> Bar:
        return Bar(self)
Run Code Online (Sandbox Code Playgroud)

这也是用于typeshed收集注释标准库的存根并顺利通过的形式mypy

Python 3.6的变量注解语法,形式:

bar: Bar = property(lambda self: Bar(self))
Run Code Online (Sandbox Code Playgroud)

mypy.

  • @z0mbi3 我不太确定你的意思?那是有效的代码。 (2认同)