Python 新手,因为习惯静态类型编程,所以写 Python 代码都会加上类型提示,便于编写。
例如以下代码:
class Node: def Link(self, node: Node) -> None: ...
这个时候,VSCode 会提示第二行的 Node 未定义,报错。而 C++ 类似的代码是可以的:
class Bundle { public: int a; void insert(Bundle another) { a += another.a; } };
有什么办法能让 Python 在这种情况下也用上类型提示吗?
![]() | 1 Dockerfile 2022-11-17 10:29:45 +08:00 ![]() def link(self, node: "Node"): 这样? |
![]() | 2 leetao94 2022-11-17 10:30:09 +08:00 ![]() 3.7 以下版本,用字符串 ```python class Node: def Link(self, node:"Node") ->"None": ... ``` 3.7 以上使用 annotations ```python from __future__ import annotations class Node: def Link(self, node: Node) -> None: ... ``` |
3 Alias4ck 2022-11-17 10:59:56 +08:00 ![]() 参考 https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class 楼上说的是第一个答案 3.11 typing 中有一个新的类型 Self 也可以避免这个问题 |
![]() | 4 sivacohan PRO ![]() 写 type hint 是一个好习惯,请务必要坚持。 |
![]() | 5 craiiz 2022-11-17 16:53:20 +08:00 NewType 先定义个一个 type ? |
6 junkun 2022-11-18 22:39:03 +08:00 3.11 之前还可以使用 typing_extensions, `from typing_extensions import Self` |