This is Module 7, where we transition from functional programming to Object-Oriented Programming (OOP). OOP is a paradigm based on the concept of “objects,” which can contain data (attributes) and code (methods). It is essential for building large-scale, maintainable software
A Class is a blueprint or a template for creating objects. An Object is an instance of a class.
Example:
Car (The blueprint)my_tesla, your_bmw (The actual physical cars)Python
class Car:
pass
my_tesla = Car() # Creating an object
__init__)The __init__ method is a special method called automatically when an object is created. It is used to initialize the object’s attributes.
Example:
Python
class Robot:
def __init__(self, name):
self.name = name # Attribute
r1 = Robot("R2-D2")
__init__).__init__).Example:
Python
class Dog:
species = "Canine" # Class variable (all dogs are canines)
def __init__(self, name):
self.name = name # Instance variable (unique name)
Methods are functions defined inside a class that describe the behaviors of the object. They always take self as the first argument, which refers to the specific instance of the object.
Python
class Bird:
def fly(self):
print("Wings flapping!")
Encapsulation hides the internal state of an object and requires all interaction to be performed through public methods. In Python, we use a double underscore __ to suggest a “private” variable.
Python
class BankAccount:
def __init__(self):
self.__balance = 0 # Private attribute
def deposit(self, amount):
self.__balance += amount
Inheritance allows a class (Child) to acquire the properties and methods of another class (Parent). This promotes code reusability.
Python
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal): # Dog inherits from Animal
def speak(self):
print("Bark!")
Polymorphism (meaning “many forms”) allows different classes to be treated as instances of the same general class through the same interface. Usually, this means different classes having the same method name but different logic.
Python
animals = [Dog(), Cat()]
for animal in animals:
animal.make_sound() # Same method name, different output based on object type
Abstraction hides complex implementation details and only shows the necessary features of an object. In Python, we use the abc (Abstract Base Classes) module to enforce this.
Method Overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class.
Example:
Python
class Parent:
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self): # Overriding
print("Inside Child")
OOP is everywhere in software development:
Player class with attributes (health, level) and methods (jump, shoot).Account class with subclasses for SavingsAccount and CheckingAccount.Button class that inherits properties from a Widget class.