Learn with diagrams, code, systems and practical examples.
Classes and Objects
Group related data and behavior into objects when the domain benefits from it.
Classes are useful when several values and operations belong to one concept such as an Order, User, or Report.
Start with the idea
A class defines structure and behavior. An object is an instance of that class with its own state. self refers to the current object inside instance methods.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
class Cart:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
cart = Cart()
cart.add("book")
print(cart.items) A class defines structure and behavior. An object is an instance of that class with its own state. self refers to the current object inside instance methods.
- Classes define object behavior.
- Instances hold state.
- Object-oriented design is a tool, not a requirement for every problem.
['book']The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Creating a class for every small piece of data even when a function or simple structure is clearer.
Use classes when state and behavior form a meaningful domain unit.
Quick recap
- Classes define object behavior.
- Instances hold state.
- Object-oriented design is a tool, not a requirement for every problem.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Create a simple Counter class.
- Add a method that changes its state.