Skip to main content

How classes work

Working with classes follows a simple pattern:
  1. Define the class - Create a blueprint with the class keyword
  2. Add an __init__ method - Set up initial data when objects are created
  3. Create instances - Make actual objects from your class
  4. Access the data - Use the attributes you defined
Let’s go through each step to build your first class.

Basic class structure

Every class starts with the class keyword:

Adding an initializer

The __init__ method runs when you create a new object:
Yes, __init__ looks weird with those double underscores! This is called a “dunder” method (double underscore). It’s just how Python works - you’ll need to type it exactly like this. Don’t worry, after writing it a few times it becomes second nature. Think of it as Python’s special way of saying “this is the setup method”.

Understanding self

self refers to the current object. It’s how an object keeps track of its own data:
When defining methods in a class, you always include self as the first parameter. But when calling the method, you don’t pass it - Python does that automatically!

Real-world example: configuration

Here’s a practical class for AI engineering:

Class vs instance

  • Class: The blueprint (like a recipe)
  • Instance/Object: What you create from the class (like a cake from the recipe)
Always use clear, descriptive names for your classes. In Python, class names use PascalCase (like TextProcessor or DataLoader), while variable names use snake_case (like text_processor or data_loader).

Common mistakes

What’s next?

Now that you understand how to create classes and store data in them, let’s learn how to add behavior with methods.

Methods and attributes

Add behavior to your classes