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
相关产品推荐
相关产品推荐

