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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:52:31