Created
January 18, 2024 19:25
-
-
Save pohlt/83cae39aee9545251c3f1573fe041e57 to your computer and use it in GitHub Desktop.
Python pattern matching of self-made classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class C: | |
__match_args__ = ("__match_self_prop__",) | |
def __init__(self, x, y=42): | |
self.x = x | |
self.y = y | |
@property | |
def __match_self_prop__(self): | |
return self | |
def __str__(self): | |
return f"C({self.x=}, {self.y=})" | |
s = C(17) | |
print("Hello world") | |
match s: | |
case int(s): | |
print("int") | |
case str(s): | |
print("string") | |
case C(s) as c: | |
print("C", c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment