Python类方法参数用自身类作类型提示触发NameError的解决方法
在类方法参数中使用自身类作为类型提示的解决方法
出现NameError: name 'Test' is not defined的原因是:在类定义过程中,类对象Test还未完全创建完成,此时直接在方法参数的类型提示中引用类名会导致名称找不到的错误。
以下是三种可行的解决方案:
1. 使用字符串形式引用类名(兼容所有Python 3版本)
将类型提示写成类名字符串,Python的类型检查器(如mypy)可正常识别这种写法:
class Test: def __eq__(self, rhs: 'Test'): # ... pass
2. 导入annotations未来特性(Python 3.7+)
通过from __future__ import annotations导入后,所有类型提示会被当作字符串处理,延迟到运行时才求值,无需手动添加引号:
from __future__ import annotations class Test: def __eq__(self, rhs: Test): # ... pass
3. 使用Self类型(Python 3.11+)
Python 3.11引入了Self类型,专门用于指代当前类,可读性更强;若使用Python 3.10及以下版本,需从typing_extensions库导入Self:
from typing import Self # Python 3.11+ # 若为Python 3.10及以下,替换为:from typing_extensions import Self class Test: def __eq__(self, rhs: Self): # ... pass
内容的提问来源于stack exchange,提问作者g00dds
相关产品推荐
相关产品推荐

