Python Lesson 19: OOP Basics
Object-Oriented Programming (OOP) is a way to organize code around “objects” — things that have data (attributes) and behaviors (methods). It makes large programs easier to manage.
The Core Idea
# In real life, a Dog has:
# Attributes: name, breed, age
# Behaviors: bark, eat, sleep
# In Python, we model this as a Class:
class Dog:
def __init__(self, name, breed, age):
self.name = name # attribute
self.breed = breed # attribute
self.age = age # attribute
def bark(self): # method (behavior)
print(f"{self.name} says: Woof!")
def describe(self): # method
print(f"{self.name} is a {self.age}-year-old {self.breed}")
Creating Objects (Instances)
# Create objects from the class
rex = Dog("Rex", "German Shepherd", 3)
bella = Dog("Bella", "Labrador", 5)
# Access attributes
print(rex.name) # Rex
print(bella.age) # 5
# Call methods
rex.bark() # Rex says: Woof!
bella.describe() # Bella is a 5-year-old Labrador
Key Concepts
# Class — the blueprint/template
# Object (Instance) — built from the blueprint
# Attribute — data stored inside an object (self.name)
# Method — function that belongs to an object
# self — refers to the current object
# __init__ — the constructor, runs when creating an object
# You can have many objects from one class:
dog1 = Dog("Max", "Poodle", 2)
dog2 = Dog("Luna", "Husky", 4)
dog3 = Dog("Charlie", "Beagle", 1)
🏋️ Practice Task
Create a BankAccount class. It should have: balance attribute (starts at 0), deposit(amount) method that adds money, withdraw(amount) method that subtracts money (check if enough funds!), get_balance() method that prints the current balance.
💡 Hint: In __init__: self.balance = 0. In deposit: self.balance += amount. In withdraw: check if amount <= self.balance first.