Python能够针对如下的一组文字或占位符进行匹配值:
choice = "apple"
match choice:
case "plum": ...
case "cherry": ...
case another_fruit:
print("Your selected fruit is:", another_fruit)但是,如果我们有一个名为another_fruit的变量,并且希望与该变量的值完全匹配,而不是为同名的占位符分配一个占位符,该怎么办?有什么特殊的语法吗?
发布于 2021-04-09 17:15:20
备选案文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
当然,如果您不介意失去一点方便,您就不必安装第三方库了:
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()是一个内置函数,用于检索本地命名空间中的所有变量。
https://stackoverflow.com/questions/67025307
复制相似问题