You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:27:10