How to use match statement with custom class?

373 Views Asked by At

The full source code is from here.

class Point:
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

How could I run the above code to obtain each case match?

I tried these:

>>> where_is((1,0))
Not a point

>>> where_is((Point))
Not a point
1

There are 1 best solutions below

0
On

In this case, the colon ":" is used to specify a type hint for the variables "x" and "y" which are public member variables in that class. They are set when declaring instances of Point() in your examples.

This explains more about type hinting: https://peps.python.org/pep-0484/