Python Classes and Object-Oriented Programming
Master Object-Oriented Programming in Python. Understand classes as blueprints, objects as instances, __init__ constructors, instance methods, and the self parameter.
Up until this point, our programs have treated data and actions as completely separate entities:
In the real world, however, things are not separated this way. An airplane is not a disconnected collection of wing parts and flying instructions; an airplane is an integrated object that possesses both attributes (fuel capacity, speed, airline) and behaviors (take off, land, turn left).
In computer programming, this way of organizing code is called Object-Oriented Programming (OOP).
1. The Blueprint Analogy: Classes vs Objects
To master OOP, you only need to understand one central analogy: The Architectural Blueprint.
CLASS (Blueprint) OBJECTS (Instances)
โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ HousePlan โ โ House 1 (Alice's) โ
โ - bedrooms: int โ โโโโโโโโโโบ โ bedrooms = 3 โ
โ - paint_color: str โ โ color = "blue" โ
โ - lock_doors() โ โโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ House 2 (Bob's) โ
โโโโโโโโโโบ bedrooms = 4 โ
โ color = "yellow" โ
โโโโโโโโโโโโโโโโโโโโโโโโโ
- A Class is the Blueprint: An architectural drawing on paper. You cannot sleep in a blueprint, and you cannot turn on its lights. It merely defines what attributes and actions future houses will have.
- An Object is the Physical House: An actual, tangible instance built from that blueprint residing in your computerโs RAM. You can build dozens of houses from a single blueprint, each with different paint colors and owners!
2. Defining a Class and Instantiating Objects
In Python, classes are defined using the class keyword. Following PEP 8 style, class names always use PascalCase (capitalizing the first letter of each word):
class Dog:
# Initializer method (Constructor)
def __init__(self, name, breed, age):
# Instance attributes
self.name = name
self.breed = breed
self.age = age
# Instance method (Behavior)
def bark(self):
print(f"{self.name} says: Woof! Woof!")
def celebrate_birthday(self):
self.age += 1
print(f"Happy Birthday {self.name}! Now {self.age} years old.")
# Creating two distinct Dog instances (objects)
dog1 = Dog("Rex", "German Shepherd", 3)
dog2 = Dog("Bella", "Golden Retriever", 2)
# Calling their behaviors
dog1.bark()
dog2.bark()
dog1.celebrate_birthday()
print(f"{dog1.name}'s age: {dog1.age}") # 4
print(f"{dog2.name}'s age: {dog2.age}") # 2 (Bella is unaffected!)
Output:
Rex says: Woof! Woof!
Bella says: Woof! Woof!
Happy Birthday Rex! Now 4 years old.
Rex's age: 4
Bella's age: 2
Notice that modifying dog1โs age had zero effect on dog2. Each object maintains its own independent state in memory!
3. Demystifying self (The #1 Question Newcomers Ask)
Beginners always ask: โWhy does every method have self as its first parameter? What does self actually mean?โ
self is a reference to the specific instance that called the method.
When you type:
dog1.bark()
Under the hood, Python translates your code into this:
Dog.bark(dog1)
Python automatically passes dog1 as the first argument into bark(). Inside the method, self represents whichever dog called the function! If dog1 called it, self.name is "Rex". If dog2 called it, self.name is "Bella".
[!NOTE] When calling an instance method, you never pass an argument for
selfyourself. Python injects it automatically behind the scenes!
4. Instance Attributes vs Class Attributes
Understanding where attributes live prevents subtle bugs:
Instance Attributes (self.attribute)
Defined inside methods using self.. They belong exclusively to that specific object:
class Employee:
def __init__(self, name, salary):
self.name = name # Unique to each employee
self.salary = salary # Unique to each employee
Class Attributes
Defined directly on the class body outside any method. They are shared by all instances of the class:
class Employee:
# Class attribute shared across all employees
company_name = "TechCorp Global"
employee_count = 0
def __init__(self, name):
self.name = name
Employee.employee_count += 1
emp1 = Employee("Alice")
emp2 = Employee("Bob")
print(emp1.company_name) # TechCorp Global
print(emp2.company_name) # TechCorp Global
print("Total staff:", Employee.employee_count) # 2
5. Practical Project: Building a Bank Account
Letโs combine these concepts into a clean, real-world object:
class BankAccount:
def __init__(self, account_holder, initial_balance=0.0):
self.holder = account_holder
self.balance = initial_balance
self.transaction_history = []
self._record_transaction("Account opened", initial_balance)
def _record_transaction(self, description, amount):
self.transaction_history.append(f"{description}: ${amount:+.2f}")
def deposit(self, amount):
if amount <= 0:
print("Deposit error: Amount must be greater than zero.")
return False
self.balance += amount
self._record_transaction("Deposit", amount)
print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")
return True
def withdraw(self, amount):
if amount > self.balance:
print(f"Declined: Insufficient funds. Available: ${self.balance:.2f}")
return False
self.balance -= amount
self._record_transaction("Withdrawal", -amount)
print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")
return True
# Using the account object:
acc = BankAccount("Alice", 100.0)
acc.deposit(50.0)
acc.withdraw(30.0)
acc.withdraw(200.0) # Declined
print("\nAudit History:")
for event in acc.transaction_history:
print(f" - {event}")
Output:
Deposited $50.00. New balance: $150.00
Withdrew $30.00. New balance: $120.00
Declined: Insufficient funds. Available: $120.00
Audit History:
- Account opened: +$100.00
- Deposit: +$50.00
- Withdrawal: -$30.00
Summary & Whatโs Next
- A class is a blueprint; an object is an instance created from that blueprint.
- The
__init__constructor sets up initial attributes when an object is instantiated. selfrefers to the specific instance invoking the method.- Instance attributes belong to individual objects; class attributes are shared across all instances.
What if you want to create a SavingsAccount that has all the features of BankAccount, but also calculates monthly interest? Rather than copy-pasting code, learn how to extend classes using inheritance.