Python Tutorial: Classes & Objects
Bundle data and behaviour together. This is where Python gets really powerful.
Your own custom types
So far you have used Python's built-in types: strings, ints, lists, dicts. But what if you need a `User`? A `Product`? A `BankAccount`?
Classes let you create your own types — bundles of data and the functions that work on that data. This is Object-Oriented Programming. Twelve steps.
What you'll learn in this Python classes & objects tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Build your own type — So far you have used Python's built-in types: strings, ints, lists, dicts.
- __init__ and self — `__init__` is the constructor — it runs automatically the moment you create an instance.
- Methods — things the object can do — Methods are functions that belong to a class. They always receive `self` first — Python passes it automatically when you…
- Class variables — shared across all instances — **Instance variables** (`self.name`) are unique per object.
- __str__ — make print() useful — When you `print(object)` without a `__str__` method, you get something like:
- Add validation to methods — One of the biggest benefits of OOP: the object can protect its own data.
- Multiple instances are independent — Every instance is a completely separate object with its own data. Changing one doesn't affect another.
- Build a shopping cart — Final challenge — no starter code.
Python Classes & Objects concepts covered
- Your own custom types