Classes & Objects (OOP)
Python fully supports object-oriented programming (OOP). Key concepts: class (blueprint), object (instance), inheritance, encapsulation, and polymorphism.
OOP lets us organize code by modeling real-world entities as objects. Each object has attributes (data) and methods (functions). A class is the blueprint that defines the attributes and methods an object has. With this approach, code becomes more structured, easier to maintain, and reusable. These concepts are very useful for large-scale projects with many interacting components.
Encapsulation hides the internal details of an object and only exposes the necessary interface, usually indicated by attributes prefixed with an underscore (_protected) or double underscore (__private). Inheritance allows a child class to inherit attributes and methods from a parent class, reducing code duplication. Polymorphism allows the same method to behave differently depending on the object calling it, achieved through method overriding.
Code Example
# Creating a class
class Cat:
# Constructor
def __init__(self, name, color):
self.name = name
self.color = color
def meow(self):
return f"{self.name}: Meow!"
def __str__(self):
return f"Cat({self.name}, {self.color})"
# Inheritance
class FunnyCat(Cat):
def __init__(self, name, color, fun_level):
super().__init__(name, color)
self.fun_level = fun_level
kitty = FunnyCat("Kitty", "orange", 100)
print(kitty.meow()) # Kitty: Meow!
print(kitty) # Cat(Kitty, orange)
Code Explanation
The Cat class is defined with an __init__ method as the constructor that accepts name and color parameters, then stores them as instance attributes (self.name and self.color). The meow() method returns the characteristic cat greeting string. The __str__ method defines the object's string representation when printed. The FunnyCat class inherits from Cat through the parentheses in the class definition, adding the fun_level attribute. The super() keyword calls the parent class's constructor so that the name and color attributes are still initialized. The kitty object is created from the FunnyCat class and inherits the meow() and __str__() methods.
Everyday Example
A library management system uses OOP to model books, members, and loans. The Book class has attributes for title, author, ISBN, and availability status. The Member class stores member data and a list of borrowed books. The EBook class inherits from Book with additional attributes for file format and size. The borrow() method on the Member class checks book availability, updates the status, and records the borrowing date. With OOP, developing new features such as late fees or loan extensions can be done without modifying existing code.
Summary
OOP in Python provides a clear and reusable structure through classes, objects, inheritance, and encapsulation. This approach is ideal for complex applications that require good code organization and easy future development.