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

传入正确参数仍报TypeError:parse_er_data()需2个参数却传3个

问题分析与解决

问题背景

这是之前参数缺失问题的后续,添加额外参数后原错误已解决,但出现新的类型错误:

@pytest.fixture
def mts_parser():
    """MTS parser fixture
    """
    mts = exchanges.get("MTS.CASH", db_write=False, filename='bondreference_20171023.txt')
>   mts.get_subparser()(mts, b'', 'context')

tests/unit/exchanges/mts/test_parser.py:27: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <exchanges.impl.mts.parser.MTSParser object at 0x7f7833257a00>, obj = Dataset MTS.CASH, data = b'', context = 'context'

    def __call__(self, obj, data, context):
        self.parser = obj
        self.logger = obj.logger
>       self.parse_er_data(data, context)
E       TypeError: parse_er_data() takes 2 positional arguments but 3 were given

exchanges/protocols/mixins.py:113: TypeError

涉及的类代码:

class Subparser:
    def __call__(self, obj, data, context):
        self.parser = obj
        self.logger = obj.logger
        self.parse_er_data(data, context)

Subparser.parse_er_data的定义:

def parse_er_data(self, data):
    raise NotImplementedError("Should be reimplemented in subparser")

疑问:之前调用mts.get_subparser()(mts, b''),且__call__中调用self.parse_er_data(data)时完全正常,为什么现在加了context参数就报错?

问题原因

你判断的完全正确:

  • 现在__call__方法调用parse_er_data(data, context)时,除了显式传入的data和context,Python会自动把self作为第一个隐含参数传递,相当于实际传了3个参数。
  • 但parse_er_data的定义只接受self和data两个参数,参数数量不匹配,因此抛出类型错误。

之前的代码没问题是因为:当时__call__只传data给parse_er_data,和方法定义的参数数量(self+data)完全匹配,所以不会报错。

解决方案

根据业务需求选择以下两种方案之一:

方案1:让parse_er_data支持context参数

如果业务逻辑需要parse_er_data使用context信息,修改基类Subparser中parse_er_data的定义,同时确保所有子类实现该方法时同步添加context参数:

def parse_er_data(self, data, context):
    raise NotImplementedError("Should be reimplemented in subparser")

方案2:调用parse_er_data时不传context参数

如果parse_er_data不需要context信息,修改__call__方法,调用时只传递data:

def __call__(self, obj, data, context):
    self.parser = obj
    self.logger = obj.logger
    self.parse_er_data(data)  # 仅传递data参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:27:12