0Pricing
Python Academy · Lesson

Class Patterns

Match against object attributes.

Class Patterns is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Matching Objects

Class patterns let match check the type of an object and pull out its attributes in one step. They look like a constructor call inside a case.

Type-Only Check

A class pattern with empty parentheses matches any instance of that class.

def kind(value):
    match value:
        case int():
            return 'an integer'
        case str():
            return 'a string'
        case _:
            return 'something else'

print(kind(5))
print(kind('hi'))
print(kind([1]))

Capturing Attributes by Name

Inside the parentheses, write attr=name to match instances and bind the named attribute to a variable.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(3, 4)

match p:
    case Point(x=px, y=py):
        print('point at', px, py)

Matching Specific Attribute Values

You can require an attribute to equal a literal. This case only matches points sitting on the x-axis.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def describe(p):
    match p:
        case Point(x=0, y=0):
            return 'origin'
        case Point(x=x, y=0):
            return 'on x-axis at ' + str(x)
        case Point():
            return 'elsewhere'

print(describe(Point(0, 0)))
print(describe(Point(5, 0)))
print(describe(Point(1, 1)))

Positional Patterns with __match_args__

If a class defines __match_args__, you can match attributes positionally. Dataclasses set this automatically from their field order.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(3, 4)

match p:
    case Point(px, py):
        print(px, py)

Defining __match_args__ Manually

For a regular class, set __match_args__ to a tuple naming the attributes you want available positionally.

class Point:
    __match_args__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

match Point(1, 2):
    case Point(a, b):
        print(a, b)

Dispatching by Class

Class patterns make a clean dispatcher over a family of related types, each handled by its own case.

from dataclasses import dataclass

@dataclass
class Circle:
    radius: float

@dataclass
class Square:
    side: float

def area(shape):
    match shape:
        case Circle(radius=r):
            return 3.14159 * r * r
        case Square(side=s):
            return s * s

print(area(Circle(2)))
print(area(Square(3)))

Nesting Class Patterns

Class patterns nest. A field that is itself an object can be matched with another class pattern.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

@dataclass
class Line:
    start: Point
    end: Point

line = Line(Point(0, 0), Point(3, 4))

match line:
    case Line(start=Point(x=0, y=0), end=Point(x=ex, y=ey)):
        print('from origin to', ex, ey)

Combining with Built-in Types

Built-in types support a single positional argument that captures the value. int(n) matches an int and binds it to n.

def label(value):
    match value:
        case int(n):
            return 'int ' + str(n)
        case str(s):
            return 'str ' + s
        case _:
            return 'other'

print(label(7))
print(label('hi'))

When to Use Class Patterns

Reach for class patterns when working with objects whose type and attribute values both drive the logic, such as event objects, AST nodes, or shape hierarchies. They replace verbose isinstance checks plus attribute access.

Mixing Positional and Keyword

You can mix positional and keyword sub-patterns in one class pattern, just like a function call. Positional ones use __match_args__ order; keyword ones name the attribute explicitly.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
    z: int

p = Point(1, 2, 3)

match p:
    case Point(x, y, z=depth):
        print(x, y, depth)

Quick Check

What does the pattern Point(x=0, y=y) match?

Recap

You learned to match against object attributes.

  • ClassName() checks the type.
  • attr=name binds attributes; literals require exact values.
  • __match_args__ enables positional matching.
  • Class patterns nest and dispatch over type hierarchies.

Frequently asked questions

Is the “Class Patterns” lesson free?

Yes — the full text of “Class Patterns” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Class Patterns”?

Match against object attributes. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Class Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. match and case Basics
  2. Matching Sequences and Mappings
  3. Class Patterns
  4. Guards and Wildcards
← Back to Python Academy