相关疑难解决方法(0)

从 __future__ 导入注释

Python 文档 __future__

在 python 文档__future__中,下面有一个表格,它显示注释在 3.7.0b1 中“可选”和“在”4.0 中“强制”,但我仍然可以在 3.8.2 中使用注释而无需导入注释,那么它的用途是什么。

>>> def add_int(a:int, b:int) -> int:
...     return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
Run Code Online (Sandbox Code Playgroud)

我怀疑我不清楚这里“可选输入”和“强制输入”的含义

python annotations python-3.x

24
推荐指数
3
解决办法
2万
查看次数

类方法返回实例的MyPy注释

我该如何注释一个@classmethod返回实例的cls?这是一个糟糕的例子:

class Foo(object):
    def __init__(self, bar: str):
        self.bar = bar

    @classmethod
    def with_stuff_appended(cls, bar: str) -> ???:
        return cls(bar + "stuff")
Run Code Online (Sandbox Code Playgroud)

这会返回一个Foo但更准确地返回Foo调用此子类的任何子类,因此使用注释-> "Foo"不够好.

python mypy

12
推荐指数
3
解决办法
3151
查看次数

标签 统计

python ×2

annotations ×1

mypy ×1

python-3.x ×1