Python 中, A 类的成员函数的参数类型是 A 类自身的时候,有什么办法能让类型提示不报错?

2022-11-17 10:23:41 +08:00
 villivateur

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 在这种情况下也用上类型提示吗?

2396 次点击
所在节点    Python
6 条回复
Jwyt
2022-11-17 10:29:45 +08:00
def link(self, node: "Node"):
这样?
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:
...
```
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 也可以避免这个问题
sivacohan
2022-11-17 12:19:49 +08:00
写 type hint 是一个好习惯,请务必要坚持。
craiiz
2022-11-17 16:53:20 +08:00
NewType 先定义个一个 type ?
junkun
2022-11-18 22:39:03 +08:00
3.11 之前还可以使用 typing_extensions, `from typing_extensions import Self`

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/895860

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX