3

Python 能够将与文字集或占位符进行匹配,如下所示:

choice = "apple"
match choice:
    case "plum": ...
    case "cherry": ...
    case another_fruit:
        print("Your selected fruit is:", another_fruit)

但是,如果我们有一个名为的变量another_fruit,并且我们希望与该变量的值完全匹配,而不是分配一个具有相同名称的占位符,该怎么办?有什么特殊的语法吗?

4

1 回答 1

3

选项1

我不知道对此的句法解决方案。裸变量名通常被认为是占位符(或者更正确地说:“捕获模式”)。

然而,有一个规则是合格的(即点)名称被认为是引用而不是捕获模式。如果您将变量存储another_fruit在这样的对象中:

fruit_object = object()
fruit_object.another_fruit = "peach"

并像这样引用它:

case fruit_object.another_fruit:
    print("It's a peach!")

它会按照你想要的方式工作。


选项 2

我最近还创建了一个名为 的库match-ref,它允许您通过点名引用任何局部或全局变量:

from matchref import ref

another_fruit = "peach"
choice = "no_peach"

match choice:
    case ref.another_fruit:
        print("You've choosen a peach!")

它通过使用 Python 的inspect模块来解析本地和全局命名空间(按此顺序)来做到这一点。


选项 3

当然,如果您可以接受失去一点便利,则不必安装 3rd-party 库:

class GetAttributeDict(dict):
    def __getattr__(self, name):
        return self[name]

def some_function():
    another_fruit = "peach"
    choice = "no_peach"
    vars = GetAttributeDict(locals())
    
    match choice:
        case vars.another_fruit:
            print("You've choosen a peach!")

GetAttributeDict使得使用点属性访问语法访问字典成为可能,并且locals()是一个内置函数,用于在本地命名空间中检索所有变量作为字典。

于 2021-04-09T17:15:20.617 回答