Python类方法出现NameError:'User'未定义问题求助
解决类方法参数类型注解引发的NameError问题
方案1:使用字符串字面量作为类型注解
在类定义内部引用自身类型时,直接用字符串"User"替代裸写的User,Python 3.7及以上版本支持这种延迟解析方式,能避开类未完全创建导致的名称找不到问题:
from sqlalchemy.orm import DeclarativeBase from sqlalchemy import Column, Integer class Base(DeclarativeBase): pass class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) @classmethod def delete(cls, user: "User"): # 编写你的删除逻辑 pass
方案2:导入annotations未来特性
从__future__导入annotations,让所有类型注解默认以字符串形式存储,直到运行时才进行解析,无需手动给类名加引号:
from __future__ import annotations from sqlalchemy.orm import DeclarativeBase from sqlalchemy import Column, Integer class Base(DeclarativeBase): pass class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) @classmethod def delete(cls, user: User): # 编写你的删除逻辑 pass
方案3:使用typing.Self(Python 3.10+)
如果你的Python版本是3.10及以上,可以直接用typing.Self来标注类自身类型,写法更直观:
from typing import Self from sqlalchemy.orm import DeclarativeBase from sqlalchemy import Column, Integer class Base(DeclarativeBase): pass class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) @classmethod def delete(cls, user: Self): # 编写你的删除逻辑 pass
内容的提问来源于stack exchange,提问作者Fred Chasin
相关产品推荐
相关产品推荐

