V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
villivateur
V2EX  ›  Python

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

  •  
  •   villivateur ·
    villivateur · 2022-11-17 10:23:41 +08:00 · 2363 次点击
    这是一个创建于 498 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    6 条回复    2022-11-18 22:39:03 +08:00
    Jwyt
        1
    Jwyt  
       2022-11-17 10:29:45 +08:00   ❤️ 1
    def link(self, node: "Node"):
    这样?
    leetao94
        2
    leetao94  
       2022-11-17 10:30:09 +08:00   ❤️ 1
    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
        3
    Alias4ck  
       2022-11-17 10:59:56 +08:00   ❤️ 1
    参考 https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class 楼上说的是第一个答案 3.11 typing 中有一个新的类型 Self 也可以避免这个问题
    sivacohan
        4
    sivacohan  
       2022-11-17 12:19:49 +08:00 via iPhone   ❤️ 3
    写 type hint 是一个好习惯,请务必要坚持。
    craiiz
        5
    craiiz  
       2022-11-17 16:53:20 +08:00
    NewType 先定义个一个 type ?
    junkun
        6
    junkun  
       2022-11-18 22:39:03 +08:00
    3.11 之前还可以使用 typing_extensions, `from typing_extensions import Self`
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5276 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 07:18 · PVG 15:18 · LAX 00:18 · JFK 03:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.