相关疑难解决方法(0)

如何使用存储在变量中的值作为案例模式?

我正在尝试了解Python 3.10 中新的结构模式匹配语法。我知道可以匹配这样的文字值:

def handle(retcode):
    match retcode:
        case 200:
            print('success')
        case 404:
            print('not found')
        case _:
            print('unknown')

handle(404)
# not found
Run Code Online (Sandbox Code Playgroud)

但是,如果我重构并将这些值移动到模块级变量,则会导致错误,因为语句现在表示结构或模式而不是值:

SUCCESS = 200
NOT_FOUND = 404

def handle(retcode):
    match retcode:
        case SUCCESS:
            print('success')
        case NOT_FOUND:
            print('not found')
        case _:
            print('unknown')

handle(404)
#  File "<ipython-input-2-fa4ae710e263>", line 6
#    case SUCCESS:
#         ^
# SyntaxError: name capture 'SUCCESS' makes remaining patterns unreachable
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 match 语句来匹配存储在变量中的值?

python switch-statement python-3.x python-3.10 structural-pattern-matching

39
推荐指数
4
解决办法
4483
查看次数

如何将大小写与类类型一起使用

我想用来match确定基于类执行的操作type。我似乎不知道该怎么做。我知道他们还有其他方法可以实现这一目标,我只是想知道是否可以通过这种方式完成。我并不是在寻找有很多的解决方法。


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)
Run Code Online (Sandbox Code Playgroud)

输出如下:

aaa
bbb
???
???
Run Code Online (Sandbox Code Playgroud)

python types class case match

10
推荐指数
2
解决办法
9698
查看次数