Match Objects with Class Patterns
Core idea
Class patterns use a class name followed by parentheses. case Parcel(weight=w): tests whether the subject is an instance of Parcel (including subclasses) and matches its weight attribute against the capture w. The syntax looks like a call but does not construct an object. Positional patterns for ordinary custom classes use __match_args__, a tuple of attribute names.
class Parcel: def __init__(self, weight): self.weight = weightmatch Parcel(6): case Parcel(weight=w): print(w)The class test succeeds and w receives the weight.
Reject a different type
class Parcel: def __init__(self, weight): self.weight = weightmatch {"weight": 6}: case Parcel(weight=w): print(w) case _: print("not a parcel")A dictionary with a similar field is not a Parcel instance.
Declare positional attributes
class Parcel: __match_args__ = ("weight",) def __init__(self, weight): self.weight = weightmatch Parcel(9): case Parcel(w): print(w)The single positional pattern corresponds to weight through match_args.
Common mistake
Constructor parameter order alone does not define positional class patterns. Without suitable match_args, a positional pattern for an ordinary custom class can raise TypeError. Prefer named attributes for clarity.
Practice
Create a Label with a text attribute. Match an instance using Label(text=t) and try matching a plain string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Read class patterns
Check your understanding of class patterns.
What is printed?
class Tag: def __init__(self, value): self.value = valuematch Tag(7): case Tag(value=n): print(n) case _: print("not a tag")What is printed?
class Tag: passmatch {"value": 7}: case Tag(value=n): print(n) case _: print("other")Which exception is raised?
class Tag: def __init__(self, n): self.n = nmatch Tag(3): case Tag(x): print(x)What does __match_args__ specify for ordinary custom classes?