Python中Match-Case匹配Point类报错的原因及解决方法
问题解决:Python match-case 匹配 Point 类实例报错
错误原因
你遇到的TypeError: Point() accepts 0 positional sub-patterns (2 given),是因为Python的match-case模式匹配中,使用位置参数(如Point(0, 0))匹配类实例时,需要类明确指定位置参数对应的实例属性——要么通过__match_args__类属性声明,要么改用关键字参数匹配。你的Point类仅定义了类型注解的属性,没有告诉匹配系统如何映射位置参数到x和y。
修复方案
方案1:给Point类添加__match_args__
修改Point类,添加__match_args__属性,指定位置参数顺序对应x和y:
class Point: __match_args__ = ('x', 'y') # 声明位置参数顺序对应x、y x: int y: int pointer = Point() pointer2 = Point() pointer.x = 0 pointer.y = 2 pointer2.x = 0 pointer2.y = 2 points = [pointer, pointer2] match points: case []: print("No points") case [Point(0, 0)]: print("The origin") case [Point(x, y)]: print("Only a single point, X={}, Y={}".format(x, y)) case [Point(0, y1), Point(0, y2)]: # 修正变量名,避免未定义错误 print("Two on Y axis, Y1={}, Y2={}".format(y1, y2)) case _: print("Something else")
这样修改后,match-case就能正确解析Point(a, b)的位置参数,对应实例的x=a、y=b。
方案2:改用关键字参数匹配
如果不想修改Point类,可以在匹配模式中用关键字参数指定属性名,这样不需要依赖__match_args__:
class Point: x: int y: int pointer = Point() pointer2 = Point() pointer.x = 0 pointer.y = 2 pointer2.x = 0 pointer2.y = 2 points = [pointer, pointer2] match points: case []: print("No points") case [Point(x=0, y=0)]: print("The origin") case [Point(x=x, y=y)]: print("Only a single point, X={}, Y={}".format(x, y)) case [Point(x=0, y=y1), Point(x=0, y=y2)]: print("Two on Y axis, Y1={}, Y2={}".format(y1, y2)) case _: print("Something else")
额外注意
你原代码中第四个case存在变量名错误:模式里写的是Point(0,y),但format里用了y1,这会导致NameError,上面的修复方案已经统一了变量名(改为y1和y2),确保变量能正确引用。
内容的提问来源于stack exchange,提问作者Daniel Ayomide AMOO
相关产品推荐
相关产品推荐

