Object-Oriented Programming (OOP) Classes, Objects, Inheritance, Polymorphism, Encapsulation

Python Basics: Object-Oriented Programming (OOP)

Python Basics: Object-Oriented Programming (OOP)

Learn to model real-world objects using classes, inheritance, and more!

1. Classes & Objects: Blueprints and Instances

Class

A class is a blueprint for creating objects. Think of it like a cookie cutter 🍪 that defines the shape of cookies.

Object

An object is an instance of a class. Each cookie made from the cutter is an object.

Example:


class Dog:  
    # Constructor (__init__) sets initial attributes  
    def __init__(self, name, breed):  
        self.name = name  
        self.breed = breed  

    # Method (action)  
    def bark(self):  
        print(f"{self.name} says Woof! 🐾")  

# Create objects  
dog1 = Dog("Buddy", "Golden Retriever")  
dog2 = Dog("Max", "Poodle")  

dog1.bark()  # Output: Buddy says Woof! 🐾  
print(dog2.breed)  # Output: Poodle  

            

2. Inheritance: Reuse Code Like a Pro

A child class inherits attributes and methods from a parent class.

Example:


class Animal:  
    def __init__(self, name):  
        self.name = name  

    def speak(self):  
        print("Sound!")  

class Cat(Animal):  # Inherits from Animal  
    def speak(self):  # Override parent method  
        print("Meow! 😸")  

class Duck(Animal):  
    def speak(self):  
        print("Quack! 🦆")  

# Create objects  
cat = Cat("Whiskers")  
duck = Duck("Daffy")  

cat.speak()  # Output: Meow! 😸  
duck.speak()  # Output: Quack! 🦆  

            

3. Polymorphism: Same Method, Different Behaviors

Objects of different classes can use the same method name but behave differently.

Example:


class Circle:  
    def draw(self):  
        print("Drawing a circle ⭕")  

class Square:  
    def draw(self):  
        print("Drawing a square ⬛")  

shapes = [Circle(), Square()]  

for shape in shapes:  
    shape.draw()  

            

Output:


Drawing a circle ⭕  
Drawing a square ⬛  

            

4. Encapsulation: Protect Your Data

Encapsulation hides internal data and exposes only what’s needed. Use private variables (with _ or __) and methods.

Example:


class BankAccount:  
    def __init__(self, balance):  
        self.__balance = balance  # Private variable  

    def deposit(self, amount):  
        self.__balance += amount  

    def get_balance(self):  # Getter method  
        return self.__balance  

account = BankAccount(100)  
account.deposit(50)  
print(account.get_balance())  # Output: 150  

# Trying to access __balance directly will fail:  
print(account.__balance)  # ❌ Error!  

            

Real-World Project: Game Characters

Create a game with characters that inherit from a base class:


class GameCharacter:  
    def __init__(self, name, health):  
        self.name = name  
        self.health = health  

    def attack(self):  
        print(f"{self.name} attacks! ⚔️")  

class Wizard(GameCharacter):  
    def cast_spell(self):  
        print(f"{self.name} casts a fireball! 🔥")  

class Archer(GameCharacter):  
    def shoot_arrow(self):  
        print(f"{self.name} shoots an arrow! 🏹")  

# Create heroes  
hero1 = Wizard("Merlin", 80)  
hero2 = Archer("Legolas", 90)  

hero1.attack()  # Output: Merlin attacks! ⚔️  
hero2.shoot_arrow()  # Output: Legolas shoots an arrow! 🏹  

            

Common Mistakes

  • ❌ Forgetting self in method definitions.
  • ❌ Misspelling __init__ (e.g., _init_ or init).
  • ❌ Overusing inheritance → Use composition sometimes!

OOP Pillars at a Glance

Pillar What It Does Example
Encapsulation Hides internal data Private variables (__balance)
Inheritance Reuse code from parent class class Cat(Animal)
Polymorphism Same method, different logic speak() for Cat vs Duck

Practice Quiz

How to make a variable private in Python?

Answer: Add __ before the name (e.g., __balance).

What’s the output?


class Bird:  
    def fly(self):  
        print("Flying! 🦅")  

class Penguin(Bird):  
    def fly(self):  
        print("Can’t fly! 🐧")  

p = Penguin()  
p.fly()  

            

Answer: Can’t fly! 🐧

Fun Activity: Build a Zoo Simulator

Create classes for Lion, Elephant, and Snake inheriting from Animal.

Add unique methods like roar(), trumpet(), and hiss().

Let users feed animals and hear their sounds!


class Lion(Animal):  
    def speak(self):  
        print("Roar! 🦁")  

zoo = [Lion("Simba"), Elephant("Dumbo")]  
for animal in zoo:  
    animal.speak()  

            

Key Takeaways

  • ✅ Classes: Blueprints for objects.
  • ✅ Objects: Instances of classes with unique data.
  • ✅ Inheritance: Share code between classes.
  • ✅ Polymorphism: Same method, different actions.
  • ✅ Encapsulation: Protect data with private variables.

What’s Next?

Learn decorators to supercharge your functions and classes!

Post a Comment

Previous Post Next Post