簡體   English   中英

如何使用 match 語句來模式匹配 python 中的多個值的類?

[英]How do I use a match statement to pattern match the class of multiple values in python?

我有一個聯合類型,我可以像這樣為它創建一個值:

import random

class X:
    s: str = 'ab'
MyType = int | X

def get_value() -> MyType:
    if random.random() > 0.5:
        return 3
    return X()

a = get_value()

我可以使用匹配語句對類進行模式匹配:

match a:
    case int():
        print(a + 1)
    case X():
        print(a.s)

但我希望能夠同時匹配多個變量。 在其他語言中執行此操作的典型方法是使用元組,但我不確定我是否正確執行此操作:

a = get_value()
b = get_value()

match a, b:
    case (int(),int()):
        print(a + 1)   # <-- Operator "+" not supported for types "MyType" and "Literal[1]"
    case (X(), X()):
        print(a.s)     # <-- Cannot access member "s" for type "int"

該代碼確實使用python3.12運行,但是當我使用語言服務器pyright 1.1.282時會顯示上述錯誤。 我的代碼有問題嗎? 有沒有一種方法可以避免我的編輯器出現診斷錯誤?

使用顯式isinstance檢查錯誤應該消失:

match a,b:
    case tuple() if isinstance(a, int):
        print(a + 1)
    case tuple() if isinstance(a, X):
        print(a.s)

暫無
暫無

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

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