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

Python 3.10中继承str的类使用match/case模式匹配失败求助

问题原因

当使用case Binge("asdf")进行模式匹配时,Python默认会沿用str类的匹配逻辑,将Binge实例与字符串"asdf"直接通过==比较。但你重写的__eq__要求比较双方必须是Binge类实例,因此返回False,导致匹配失败。同时你需要保留Binge('a') == Binge('a')和Binge('a') != 'a'的核心业务逻辑。

解决方案

通过自定义__match_args__属性和对应的属性方法,让模式匹配时直接比较字符串值,绕过重写的__eq__,同时完全保留原有==行为:

class Binge(str):
    # 指定模式匹配位置参数对应的属性名
    __match_args__ = ('value',)

    def __eq__(self, other):
        return self.__class__ == other.__class__ and str.__eq__(self, other)

    def __ne__(self, other):
        return not self == other

    @property
    def value(self):
        # 返回实例对应的字符串值
        return str(self)


# 核心断言依然成立
assert Binge('a') == Binge('a')
assert Binge('a') != 'a'

# 模式匹配生效
matched = False
match Binge("asdf"):
    case Binge("asdf"):
        matched = True
assert matched
原理说明
  • __match_args__ = ('value',)告诉Python,当使用case Binge(arg)的模式时,需要将实例的value属性与arg进行比较。
  • 定义的value属性返回实例的字符串值,此时比较的是两个str对象,直接使用内置的字符串相等逻辑,与你重写的__eq__无关。
  • 原有__eq__逻辑完全保留,确保Binge实例仅与同类型实例比较字符串值,满足你的核心业务需求。

内容的提问来源于stack exchange,提问作者Joshua D. Boyd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:05:17