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

为什么SQLAlchemy Postgres ORM的声明式基类需要自定义__init__方法

错误根本原因

SQLAlchemy 声明式映射类自动生成的默认__init__方法仅支持关键字参数传值,不接受位置参数。你在insert.py中初始化NumLimit实例时使用的是位置参数传参,不符合默认构造方法的规则,因此会触发参数数量不匹配的TypeError。你之前怀疑的scoped_session逻辑、基类继承逻辑均无问题。

修复方案

方案1:删除自定义__init__,修改实例化传参方式

将insert.py中NumLimit的实例化代码改为关键字参数传值即可,无需自定义构造方法:

a_num_limit = NumLimit(
    org='123e4567-e89b-12d3-a456-426614174000',
    limits=20,
    limits_rate=4,
    rate_use=8
)
another_limit = NumLimit(
    org='123e4567-e89b-12d3-a456-426614174660',
    limits=7,
    limits_rate=2,
    rate_use=99
)

方案2:保留自定义__init__,修正笔误

你当前写的自定义__init__存在参数不匹配的笔误:参数列表里的allowance_rate、usage、last_usage未被使用,赋值时用到的limits_rate不在参数列表中,实际运行会触发NameError,修正后即可正常使用:

# 修正后的__init__示例
def __init__(self, org, limits, limits_rate, rate_use):
    super().__init__()
    self.org = org
    self.limits = limits
    self.limits_rate = limits_rate
    self.rate_use = rate_use

内容的提问来源于stack exchange,提问作者alphaomega

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:36:02