Loading notes...
Loading notes...
BCA • Chapter 9
Chapter 9 covers Object-Oriented Programming (OOP) in Python, focusing on Classes, Objects, the __init__ constructor, Encapsulation, Inheritance, and Polymorphism.
Procedural programming involves writing sequences of instructions to act upon data. As applications scale, managing disconnected functions and global variables becomes chaotic. Object-Oriented Programming (OOP) is a paradigm that binds data and the functions that operate on that data together into a single unit called an Object. This approach models real-world entities, making code far more organized, reusable, and scalable.
9.1 Classes and Objects
A Class is a blueprint or template for creating objects. It defines the structure (attributes/variables) and behaviors (methods/functions) that the objects created from it will possess. An Object is a concrete instance of a class. You can create hundreds of distinct objects from a single class.
# Defining a Class
class Car:
# The __init__ method is the Constructor.
# It is called automatically when a new object is created.
def __init__(self, brand, color):
# 'self' refers to the specific object being created
self.brand = brand # Attribute
self.color = color # Attribute
self.is_running = False
# A Method (a function belonging to the class)
def start_engine(self):
self.is_running = True
print(f"The {self.color} {self.brand} engine is started.")
# Instantiating (creating) Objects
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")
# Accessing attributes and calling methods
print(car1.brand) # Output: Toyota
car2.start_engine() # Output: The Blue Honda engine is started.9.2 The Four Pillars of OOP
Object-Oriented Programming is built upon four fundamental principles:
9.3 Encapsulation and Data Hiding
Unlike Java or C++, Python does not have strict 'private' or 'protected' access modifiers. Instead, Python relies on a naming convention. Prefixing an attribute with a single underscore `_` signals that it is meant for internal use (protected). Prefixing with a double underscore `__` invokes 'name mangling', heavily discouraging external access (private).
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute (double underscore)
# Public method acting as a getter
def get_balance(self):
return self.__balance
# Public method acting as a setter with validation
def deposit(self, amount):
if amount > 0:
self.__balance += amount
account = BankAccount("Basant", 1000)
print(account.owner) # Works fine
# print(account.__balance) # Raises AttributeError! Cannot access directly
print(account.get_balance()) # Output: 1000 (Safe access)9.4 Inheritance and Super()
Inheritance allows a child class to absorb everything from a parent class. The child can then add its own unique attributes or override parent methods. The `super()` function is used inside the child class to invoke methods (especially `__init__`) from the parent class.
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
# Child Class inheriting from Animal
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call Parent's __init__ to set 'name'
self.breed = breed
# Method Overriding: Replacing the parent's speak method
def speak(self):
return "Woof!"
my_dog = Dog("Buddy", "Golden Retriever")
print(f"{my_dog.name} is a {my_dog.breed} and says {my_dog.speak()}")
# Output: Buddy is a Golden Retriever and says Woof!9.5 Polymorphism
Polymorphism (Many Forms) allows functions to accept objects of different classes, as long as they implement the expected method. Python naturally supports duck typing ('If it walks like a duck and quacks like a duck, it must be a duck').
class Cat(Animal):
def speak(self):
return "Meow!"
# This function demonstrates polymorphism.
# It doesn't care if 'pet' is a Dog, Cat, or any other Animal,
# as long as it has a speak() method.
def make_pet_speak(pet):
print(pet.speak())
make_pet_speak(Dog("Max", "Pug")) # Output: Woof!
make_pet_speak(Cat("Luna")) # Output: Meow!