在 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)
我怀疑我不清楚这里“可选输入”和“强制输入”的含义
我该如何注释一个@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"不够好.