簡體   English   中英

在結構模式匹配的默認情況下如何訪問匹配的值?

[英]How to access the matched value in the default case of structural pattern matching?

使用 Python 3.10 的 match 語句,是否可以使用默認情況下遇到的值?

或者這是否需要在match之前分配一個變量以便可以在默認情況下使用?

match expensive_calculation(argument):
    case 'APPLE':
        value = 'FOO'
    case 'ORANGE':
        value = 'BAR'
    case _:
        raise Exception(
           "Wrong kind of fruit found: " +
           str(expensive_calculation(argument))
           # ^ is it possible to get the default value in this case?
        )

您可以使用as模式

match expensive_calculation(argument):
  case 'APPLE':
    value = 'FOO'
  case 'ORANGE':
    value = 'BAR'
  case _ as argument: #here, using `as` to save the wildcard default to `argument`
    raise Exception(f"Wrong kind of fruit found: {str(argument)}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM