Python Classes and Objects
Table of Contents
In the last lesson, we learned about Python Introduction to OOP. After learning what OOP is, let us learn about classes and objects in Python. Classes are blueprints. Objects are the things we build from them.
In this tutorial, we will learn how to define a class, create objects, and use them.
ποΈ What Is a Class in Python?
A class is a blueprint for creating objects. It defines what data and methods the objects will have.
Think of a class like a cookie cutter. It defines the shape. But it is not the cookie itself.
We define a class using the class keyword.
class Dog: passThat is the simplest class. It does nothing. But it is a valid class.
π§© What Is an Object in Python?
An object is an instance of a class. It is the actual thing we create from the blueprint.
If the class is a cookie cutter, the object is the cookie.
We create an object by calling the class like a function.
class Dog: pass
my_dog = Dog()Now my_dog is an object of the Dog class.
We can create many objects from one class.
dog1 = Dog()dog2 = Dog()dog3 = Dog()Each one is a separate object. They do not interfere with each other.
π§ Adding Attributes to a Class in Python
A class can have attributes. These are variables that belong to the object.
We can set attributes on an object directly.
class Dog: pass
my_dog = Dog()my_dog.name = "Buddy"my_dog.age = 3
print(my_dog.name)print(my_dog.age)Output
Buddy3That works. But it is not the best way. Because we have to set attributes every time we create an object.
A better way is to use a constructor. We will learn about that in the next tutorial.
π‘ Adding Methods to a Class in Python
A method is a function that belongs to a class. It can use the objectβs data.
We define methods inside the class. The first parameter is always self.
class Dog: def bark(self): print("Woof!")
my_dog = Dog()my_dog.bark()Output
Woof!The self parameter refers to the object itself. So inside the method, we can access the objectβs attributes.
class Dog: def bark(self): print(f"{self.name} says Woof!")
my_dog = Dog()my_dog.name = "Buddy"my_dog.bark()Output
Buddy says Woof!That is how we use methods with object data.
π§ͺ How to Create Multiple Objects in Python
We can create many objects from one class. Each object has its own data.
class Dog: def bark(self): print(f"{self.name} says Woof!")
dog1 = Dog()dog1.name = "Buddy"
dog2 = Dog()dog2.name = "Max"
dog1.bark()dog2.bark()Output
Buddy says Woof!Max says Woof!Both dogs have their own names. But they share the same bark method.
π A Real-Life Example β Bank Account
Letβs create a simple bank account class.
class BankAccount: def deposit(self, amount): self.balance += amount print(f"Deposited {amount}. New balance: {self.balance}")
def withdraw(self, amount): if amount > self.balance: print("Insufficient funds") else: self.balance -= amount print(f"Withdrew {amount}. New balance: {self.balance}")
account = BankAccount()account.balance = 1000
account.deposit(500)account.withdraw(200)account.withdraw(2000)Output
Deposited 500. New balance: 1500Withdrew 200. New balance: 1300Insufficient fundsThat is a simple bank account. It has data (balance) and methods (deposit, withdraw).
π Common Mistakes with Classes and Objects in Python
β Mistake 1: Forgetting self in method definitions
class Dog: def bark(): print("Woof!")This gives an error when we call bark().
Fix:
class Dog: def bark(self): print("Woof!")π« Mistake 2: Forgetting to call the class to create an object
class Dog: def bark(self): print("Woof!")
my_dog = Dogmy_dog.bark()This gives an error. Because my_dog is the class, not an object.
Fix:
my_dog = Dog()my_dog.bark()π Mistake 3: Setting attributes on the class instead of the object
class Dog: pass
Dog.name = "Buddy"my_dog = Dog()print(my_dog.name)This works. But it sets the attribute on the class, not the object. So all objects share the same name.
Fix: Set attributes on the object.
my_dog = Dog()my_dog.name = "Buddy"Next, we will learn about Python Constructors and set starting data when an object is created.