[Python] How to use match case with a class type

Discussão em 'Python' iniciado por Stack, Julho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I want to use match to determine an action to perform based on a class type. I cannot seem to figure out how to do it. I know their are other ways of achieving this, I would just like to know can it be done this way. I am not looking for workarounds of which there are many.


    class aaa():
    pass

    class bbb():
    pass

    def f1(typ):
    if typ is aaa:
    print("aaa")
    elif typ is bbb:
    print("bbb")
    else:
    print("???")

    def f2(typ):
    match typ:
    case aaa():
    print("aaa")
    case bbb():
    print("bbb")
    case _:
    print("???")

    f1(aaa)
    f1(bbb)
    f2(aaa)
    f2(bbb)


    The output is as follows:

    aaa
    bbb
    ???
    ???

    Continue reading...

Compartilhe esta Página