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

Python中如何正确初始化继承SQLAlchemy Table的子类

SQLAlchemy Table子类初始化报错TypeError解决方法

问题背景

作为Python新手,尝试初始化Cpty子类时仅传入SQLAlchemy engine参数,其余属性由父类配置,但执行cpty = Cpty(connection.engine)时触发TypeError异常。

现有代码结构

default_table.py

from sqlalchemy import Table, MetaData

class Default_table(Table):

    def __init__(self, table_name, autoload, autoload_with):
        metadata = MetaData(schema='dbo')
        super(Default_table, self).__init__(table_name, metadata, autoload=autoload, autoload_with=autoload_with)

    def output(self):
        print('ahoj')

counterparty.py

from .default_table import Default_table

class Cpty(Default_table):

    def __init__(self, engine):
        table_name = 'CPTY'
        autoload = True
        super(Cpty, self).__init__(table_name, autoload=autoload, autoload_with=engine)

报错信息

Exception has occurred: TypeError
Table() takes at least two positional-only arguments 'name' and 'metadata'

问题原因

SQLAlchemy的Table类实例化逻辑主要在__new__方法中处理,而非普通Python类的__init__方法。直接继承Table并重写__init__会干扰它原本的初始化流程,导致缺少必要的位置参数(name和metadata)。

解决方案

修改父类和子类的实现,改用重写__new__方法来传递参数,适配Table类的实例化逻辑:

修改后的default_table.py

from sqlalchemy import Table, MetaData

class Default_table(Table):
    # 重写__new__方法来创建Table实例
    def __new__(cls, table_name, autoload_with):
        metadata = MetaData(schema='dbo')
        # 调用父类__new__传递必要参数
        return super().__new__(cls, table_name, metadata, autoload=True, autoload_with=autoload_with)
    
    def output(self):
        print('ahoj')

修改后的counterparty.py

from .default_table import Default_table

class Cpty(Default_table):
    def __new__(cls, engine):
        # 调用父类__new__,传入表名和engine
        return super().__new__(cls, 'CPTY', engine)

现在执行cpty = Cpty(connection.engine)即可正常初始化,同时保留父类中定义的metadata配置和output方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:30:45