Mastering Python Object‑Oriented Programming: Classes, Inheritance, Encapsulation & Polymorphism
Python Object‑Oriented Programming
This guide walks you through the core concepts of Python’s Object‑Oriented Programming (OOP), complete with practical examples that illustrate how to build robust, reusable code.
Video: Object‑Oriented Programming in Python
Object‑Oriented Programming
Python is a multi‑paradigm language that supports several programming styles. One of the most powerful approaches is to model problems using objects—an approach known as Object‑Oriented Programming (OOP).
An object possesses two essential characteristics:
- Attributes (data)
- Behavior (methods)
For instance, a parrot is an object with attributes such as name, age, and color, and behaviors like sing() and dance().
OOP in Python promotes reusable code, adhering to the DRY (Don’t Repeat Yourself) principle.
Class
A class is a blueprint that defines the structure and behavior of objects. Think of it as a detailed sketch of a parrot: it specifies what properties and actions a parrot can have.
class Parrot:
pass
Here, Parrot is an empty class. Instances of this class are created later.
Object
An object (or instance) is a concrete realization of a class. When a class is defined, no memory is allocated; only the template exists. Instantiating the class creates the object.
obj = Parrot()
In the example below, we build a functional Parrot class and create two instances, blu and woo:
class Parrot:
# Class attribute
species = "bird"
# Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# Access class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# Access instance attributes
print("{} is {} years old".format(blu.name, blu.age))
print("{} is {} years old".format(woo.name, woo.age))
Output
Blu is a bird Woo is also a bird Blu is 10 years old Woo is 15 years old
In this snippet, species is a class attribute shared by all parrots, whereas name and age are instance attributes unique to each object.
Methods
Methods are functions defined within a class that describe object behavior. They are invoked on instances of the class.
class Parrot:
def __init__(self, name, age):
self.name = name
self.age = age
def sing(self, song):
return f"{self.name} sings {song}"
def dance(self):
return f"{self.name} is now dancing"
# Instantiate and use methods
blu = Parrot("Blu", 10)
print(blu.sing("'Happy'"))
print(blu.dance())
Output
Blu sings 'Happy' Blu is now dancing
Inheritance
Inheritance lets a new class inherit attributes and methods from an existing class, promoting code reuse and logical hierarchy.
# Base class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# Derived class
class Penguin(Bird):
def __init__(self):
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Output
Bird is ready Penguin is ready Penguin Swim faster Run faster
Encapsulation
Encapsulation restricts direct access to an object’s internal state, protecting data integrity. In Python, private attributes are denoted by a leading underscore (single or double).
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print(f"Selling Price: {self.__maxprice}")
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# Attempt to modify directly
c.__maxprice = 1000
c.sell()
# Use setter method
c.setMaxPrice(1000)
c.sell()
Output
Selling Price: 900 Selling Price: 900 Selling Price: 1000
Polymorphism
Polymorphism allows objects of different classes to be treated through a shared interface, enabling flexible code that can operate on various object types.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# Common interface
def flying_test(bird):
bird.fly()
blu = Parrot()
peggy = Penguin()
flying_test(blu)
flying_test(peggy)
Output
Parrot can fly Penguin can't fly
Key Takeaways
- OOP structures code for clarity and maintainability.
- Classes enable code reuse through inheritance.
- Encapsulation safeguards internal data.
- Polymorphism offers flexible interfaces across object types.
Python
- C# Classes & Objects: Foundations for Robust OOP
- Mastering Python Custom Exceptions: A Practical Guide
- Mastering Python Inheritance: Concepts, Syntax, and Practical Examples
- Master Python Multiple Inheritance, Multilevel Inheritance, and Method Resolution Order (MRO)
- Python OOP Fundamentals: Classes, Objects, Inheritance, and Constructors Explained
- Mastering Python Class Slots: Optimize Memory & Speed
- Master Python's Object-Oriented Programming: A Comprehensive Guide
- Python Network Programming: Master Sockets & Advanced Protocols
- Master Python Multithreaded Programming: Efficient Concurrency Techniques
- Master Python Extension Programming with C: Build Fast, Native Modules