gpt4 book ai didi

Python 类型注解 : Any way to annotate a property?

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:38 25 4
gpt4 key购买 nike

我正在定义一个 Python 类:

class Foo:
bar = property(lambda self: Bar(self))

我想注释 bar 属性,说明它包含 Bar 类的项目。有一种公认的方法吗?我知道这是有效的 Python 语法:

bar: Bar = property(lambda self: Bar(self))

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

最佳答案

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

class Foo:
@property
def bar(self) -> Bar:
return Bar(self)

这也是 typeshed 中使用的形式它收集了注释标准库的 stub ,也顺利地通过了 mypy

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

bar: Bar = property(lambda self: Bar(self))

目前在使用 mypy 检查时是可以接受的。

关于Python 类型注解 : Any way to annotate a property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42463443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com