point=(5,6) match point: case (0, 0): print("Origin") case (0, y): print(f"Y={y}") case (x, 0): print(f"X={x}") case (x, y): print(f"X={x}, Y={y}") case _: raise ValueError("Not a point")
classPoint(): def__init__(self,x,y): self.x = x self.y = y deflocation(point): match point: case Point(x=0, y=0): print("Origin is the point's location.") case Point(x=0, y=y): print(f"Y={y} and the point is on the y-axis.") case Point(x=x, y=0): print(f"X={x} and the point is on the x-axis.") case Point(): print("The point is located somewhere else on the plane.") case _: print("Not a point") point = Point(0, 1) location(point)
if 子句模式:
1 2 3 4 5 6
point = Point(x=0,y=0) match point: case Point(x=x, y=y) if x == y: print(f"The point is located on the diagonal Y=X at {x}.") case Point(x=x, y=y): print(f"Point is not on the diagonal.")
复杂模式和通配符:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
deffunc(person): match person: case (name,"teacher"): print(f"{name} is a teacher.") case (name, _, "male"): print(f"{name} is man.") case (name, _, "female"): print(f"{name} is woman.") case (name, age, gender): print(f"{name} is {age} old.") func(("Sam", "teacher")) func(("John", 25, "male")) func(("John", 25, "man")) func(["John", 25, "female"])