Python Classes and Objects for Beginners
What Are Classes and Objects in Python?
A class is a blueprint: a plan that says what a kind of thing has and what it can do. An object is one real thing built from that blueprint. Writing programs around classes and objects is called object-oriented programming, or OOP for short.
Think of it like a cookie cutter. The cutter is the class: it gives every cookie the same shape. Each cookie you press out is an object. They all share the shape, but each one is its own cookie, and you can put different icing on each.
| Idea | Real life | Python |
|---|---|---|
| Class | the blueprint of a house | class Dog: |
| Object | one house built from it | rocky = Dog() |
- One class can make as many objects as you like.
- Every object made from a class has the same parts, but its own values: Rocky and Lucky are both dogs, with different names.
- An object keeps data (what it has, like a name) and actions (what it can do, like bark) together, in one place.
You've used objects all along
Every value in Python is an object. "sunny" is an object made from the class str. A list is an object made from the class list. And upper() and append() are actions those objects can do:
name = "sunny"
print(name.upper())
pets = ["Rocky"]
pets.append("Lucky")
print(pets)SUNNY ['Rocky', 'Lucky']
In this chapter, you'll make your own classes, like Dog, Student and BankAccount, each with its own data and actions.
Common beginner doubt: "Do I need classes to write programs?" No. Everything you've built so far worked without them. Classes help when a program has many things of the same kind, like 30 students or 100 bank accounts, each with its own data.
A class is the blueprint; an object is one thing built from it.