PYTHON · 기초 문법
match/case 패턴 매칭 (Python 3.10+)
구조적 패턴 매칭. 단순 switch 이상의 강력한 패턴 분해를 제공합니다.
기초 문법중급matchcasepattern-matchingstructuralPython 3.10
핵심 설명
구조적 패턴 매칭. 단순 switch 이상의 강력한 패턴 분해를 제공합니다.
Python code
# 기본 match/case
def http_status(status):
match status:
case 200: return "OK"
case 404: return "Not Found"
case 500 | 503: return "Server Error" # OR 패턴
case _: return "Unknown"
# 구조 분해 패턴
def process_command(command):
match command.split():
case ["quit"]:
return "종료"
case ["go", direction]:
return f"{direction}(으)로 이동"
case ["go", direction, speed]:
return f"{direction}으로 {speed} 속도로 이동"
case _:
return "알 수 없는 명령"
# 클래스 패턴
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def where_is(point):
match point:
case Point(x=0, y=0): return "원점"
case Point(x=0, y=y): return f"Y축 위 {y}"
case Point(x=x, y=0): return f"X축 위 {x}"
case Point(x=x, y=y): return f"({x}, {y})"
print(where_is(Point(0, 5))) # Y축 위 5
print(process_command("go north fast"))학습 팁
case에서 변수에 바인딩하려면 이름 앞에 아무것도 붙이지 않으면 됩니다. 상수와 비교하려면 Enum이나 클래스.속성 형태를 사용하세요.
주의할 점
case status_code처럼 단독 이름을 쓰면 상수 비교가 아니라 변수 바인딩이 됩니다. 상수와 비교하려면 case MyEnum.VALUE 형태를 사용하세요.
자주 묻는 질문
match/case 패턴 매칭 (Python 3.10+)란 무엇인가요?
구조적 패턴 매칭. 단순 switch 이상의 강력한 패턴 분해를 제공합니다.
match/case 패턴 매칭 (Python 3.10+) 학습 시 주의할 점은 무엇인가요?
case status_code 처럼 단독 이름을 쓰면 상수 비교가 아니라 변수 바인딩이 됩니다. 상수와 비교하려면 case MyEnum.VALUE 형태를 사용하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.