我一直在研究我的代码的类型提示,但注意到 Python 程序员通常不会self在他们的程序中输入提示
即使当我查看文档时,他们似乎也没有输入提示 self,请参见 此处。这是来自 3.10 版的后向声明
def __init__(self, value: T, name: str, logger: Logger) -> None:
我可以理解为什么在 3.7 中使用前向声明引入类型注释之前这是一个问题
这对我来说似乎有用的原因是 mypy 似乎能够捕捉到这个问题的错误
例子:
from __future__ import annotations
class Simple(object):
def __init__(self: Simple):
print(self.x)
会从 mypy 返回这个
mypy test.py
test.py:5: error: "Simple" has no attribute "x"
Found 1 error in 1 file (checked 1 source file)
如果您从中删除类型,self则变为
Success: no issues found in 1 source file
- 是否有
self没有注释的原因或者这是唯一的约定? - 是否存在我遗漏的权衡,或者
self由于某种原因我的注释错误?