How classes work
Working with classes follows a simple pattern:- Define the class - Create a blueprint with the
classkeyword - Add an
__init__method - Set up initial data when objects are created - Create instances - Make actual objects from your class
- Access the data - Use the attributes you defined
Basic class structure
Every class starts with theclass 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
Forgetting self in __init__
Forgetting self in __init__
Not using self for attributes
Not using self for attributes
Forgetting parentheses when creating instance
Forgetting parentheses when creating instance
Modifying class instead of instance
Modifying class instead of instance
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