Build garageTry it → read → next · ~10 min

Tutorials · Chapter D (4/4) · ~10 min

Classes and objects

Try it → see it → read → next

Bundle data and behavior into a reusable Python object you can inspect and call.

Try yourself

Playground

Object form builder

Build a Message class mentally: fields role + content, then call preview().

class Message:
  # role…
  # content…
  # preview()…

Recap

What you just did

ObjectFormBuilder bundled fields and a preview() method — objects as data plus behavior.

Teach

How it works

class TinyModel:
    def __init__(self, name, threshold=0.5):
        self.name = name
        self.threshold = threshold

    def predict(self, score):
        return score >= self.threshold

strict = TinyModel("strict", 0.8)
friendly = TinyModel("friendly", 0.4)
print(strict.predict(0.6), friendly.predict(0.6))
  1. Class defines shared structure and behavior
  2. __init__ sets up a new instance
  3. self means “this particular object”
  4. Method is a function called through the object

Mental model: a class is a cookie cutter; objects are separate cookies that can carry different toppings.

Use it

When you'd use this

  • Keeping model settings beside a predict method
  • Creating several data loaders with different file paths
  • Understanding library code such as client.responses.create(...)

Watch out

Watch out

Forgetting self in a method is a common first error. Also, class attributes can be shared accidentally; put per-object lists and dictionaries inside __init__ so one instance does not silently change another.

Try next

Try this next

Add a describe method that returns the model’s name and threshold. Call it on both objects.