Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Master Object Oriented Programming in Python

Learn OOP principles in Python with real-world examples and tips

7 min readNov 25, 2024

--

Press enter or click to view image in full size
Image created by me, CyCoderX, feel free to connect with me on my socials!

Object-Oriented Programming (OOP) is a widely-used programming paradigm that helps developers design more structured, reusable, and maintainable code.

In traditional programming, you might work with functions and variables that operate independently. But with OOP, you group related functions (called methods) and data (called attributes) into objects. These objects can be modelled to represent real-world entities, allowing you to simulate complex systems in a more intuitive way.

Think of OOP as a way to organize your code by breaking it down into smaller, self-contained components, each representing a specific “thing” or “concept” in your application. For instance, in a game, you could have Player, Enemy, and Weapon objects, each with their own set of attributes (like health or damage) and methods (like attack() or move()).

But why do we need OOP in the first place?

OOP helps to solve problems that arise when your programs become large or complex. By structuring your code into classes and objects, you can:

  • Organize and modularize your code, making it easier to read and maintain.
  • Reuse code by creating new objects based on existing blueprints.
  • Extend functionality by building upon existing objects without having to modify them.
  • Create more scalable programs that can grow without becoming chaotic.

In this article, we will cover the key principles of OOP in Python and learn how to:

  1. Define Classes and Create Objects: Learn how to model real-world entities as Python classes and instantiate objects.
  2. Work with Attributes and Methods: Understand how to define and use attributes (data) and methods (functions) within a class.
  3. Use Encapsulation: Discover how to hide the internal workings of objects to protect data and reduce complexity.
  4. Implement Inheritance: Learn how to extend existing classes and reuse code efficiently.
  5. Apply Polymorphism: See how to implement different behaviors while using the same method name.
  6. Explore Advanced OOP Concepts: We will also look at overriding methods, and how to use the super() function to access parent class functionality.

By the end of this article, you will have a solid understanding of how OOP works in Python and be able to apply these concepts to build more modular, reusable, and scalable software.

Let’s dive in!

Hi, my name is CyCoderX! I write articles about Python, SQL, Data Engineering and Data Science content. Please consider helping me out by following me.😊

Introduction

At its core, OOP revolves around a few key concepts:

  1. Classes and Objects
  2. Attributes and Methods
  3. Encapsulation
  4. Inheritance
  5. Polymorphism

Why Use OOP?

OOP provides several advantages:

  • Modularity: Code is organized into classes and objects, making it easier to manage and maintain.
  • Reusability: Objects and classes can be reused across programs or projects.
  • Scalability: OOP is great for larger projects, as it encourages modular, scalable code.

Classes and Objects

In Python, think of classes as blueprints for creating objects. An object is an instance of a class, and the class defines the structure and behavior of its objects.

Creating a Class and Object

Let’s start by defining a simple class for a Car:

# Defining a class
class Car:
# Constructor method to initialize attributes
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

# Method to display car details
def car_details(self):
return f"{self.year} {self.brand} {self.model}"

# Creating an object (instance) of the Car class
my_car = Car("Tesla", "Model S", 2022)

# Accessing the car's details
print(my_car.car_details()) # Output: 2022 Tesla Model S

Explanation:

  • Class Car: A class that models a car, with attributes for the car’s brand, model, and year.
  • Constructor __init__: This special method is automatically called when we create an object, initializing the attributes of the object.
  • Method car_details(): This is a function within the class that provides details about the car.
  • Object my_car: An instance of the Car class, representing a specific car.

Attributes and Methods

  • Attributes: These are variables that belong to a class or object. In the Car class, brand, model, and year are attributes.
  • Methods: Functions that belong to a class are called methods. In the Car example, car_details() is a method.

Example with Multiple Methods:

class Car:
def __init__(self, brand, model, year, mileage=0):
self.brand = brand
self.model = model
self.year = year
self.mileage = mileage

def drive(self, miles):
"""Adds miles to the car's mileage."""
self.mileage += miles
print(f"You drove {miles} miles. Total mileage: {self.mileage}")

# Create another object
my_suv = Car("Toyota", "RAV4", 2021)

my_suv.drive(150) # You drove 150 miles. Total mileage: 150

Here, the drive() method allows us to simulate adding mileage to the car. Each car object can have different mileage, but they share the same behavior.

Encapsulation

Encapsulation means bundling the data (attributes) and methods (functions) that operate on the data into a single unit, the class. It also allows you to hide the internal representation of an object from the outside world (known as data hiding).

Private Attributes

In Python, we can make attributes “private” by prefixing them with two underscores (__). Private attributes can't be directly accessed from outside the class:

class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
self.age = age # Public attribute

def get_name(self):
"""Getter method to access the private attribute."""
return self.__name

# Creating an object
person = Person("Alice", 30)

print(person.age) # 30 (accessible)
print(person.get_name()) # Alice (accessed via method)
# print(person.__name) # Error: 'Person' object has no attribute '__name'

In this example:

  • __name is a private attribute and can only be accessed via the get_name() method.
  • We use a getter method to access private attributes safely.

Inheritance

Inheritance allows one class (child class) to inherit the properties and methods of another class (parent class). This helps avoid code duplication and allows for a hierarchical organization of classes.

Example of Inheritance:

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

def sound(self):
pass # To be defined by subclasses

# Child class inheriting from Animal
class Dog(Animal):
def sound(self):
return f"{self.name} says Woof!"

# Another child class
class Cat(Animal):
def sound(self):
return f"{self.name} says Meow!"

# Creating objects of child classes
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.sound()) # Buddy says Woof!
print(cat.sound()) # Whiskers says Meow!

In this example:

  • Animal is the parent class with a placeholder method sound().
  • Dog and Cat are child classes that inherit from Animal and provide specific implementations of sound().

Polymorphism

Polymorphism allows different classes to define the same method, but each behaves differently depending on the class object. This is demonstrated in the sound() method in the previous example where both Dog and Cat have a method sound(), but the output is different.

Polymorphism Example with a Common Interface:

def animal_sound(animal):
print(animal.sound())

# Using the same interface for different objects
animal_sound(dog) # Buddy says Woof!
animal_sound(cat) # Whiskers says Meow!

Here, the animal_sound() function takes an animal object and calls its sound() method. The function works for both Dog and Cat objects, demonstrating polymorphism.

Advanced OOP Features: Method Overriding and Super()

  • Method Overriding: A child class can override a method from the parent class to change its behavior.
  • super() Function: The super() function allows you to call a method from the parent class inside a child class.

Example of Method Overriding with super():

class Vehicle:
def __init__(self, brand, year):
self.brand = brand
self.year = year

def info(self):
return f"{self.year} {self.brand}"

class Truck(Vehicle):
def __init__(self, brand, year, load_capacity):
super().__init__(brand, year)
self.load_capacity = load_capacity

def info(self):
parent_info = super().info() # Call parent class's info()
return f"{parent_info}, Load Capacity: {self.load_capacity} tons"

# Creating an object of Truck
my_truck = Truck("Ford", 2019, 15)
print(my_truck.info()) # 2019 Ford, Load Capacity: 15 tons

In this example:

  • The Truck class overrides the info() method from the Vehicle class.
  • The super() function is used to call the parent class’s info() method.

Conclusion

Object-Oriented Programming in Python makes it easier to organize code, especially as projects grow in complexity. It offers powerful tools for structuring your programs with:

  • Classes and objects to model real-world entities,
  • Encapsulation to protect data,
  • Inheritance to reuse and extend code,
  • Polymorphism to allow flexibility in method behavior.

By mastering OOP, one can create more modular, maintainable, and scalable code!

Get CyCoderX’s stories in your inbox

Join Medium for free to get updates from this writer.

Always remember to conduct your own research and verify the information you encounter. Relying solely on others can result in outdated or incorrect practices. Take the initiative to implement and refine the code you find, ensuring it meets your specific needs and standards.

Press enter or click to view image in full size
Photo by Etienne Girardet on Unsplash

Final Words:

Thank you for taking the time to read my article.

This article was first published on Medium by CyCoderX.

Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!

If you want to explore similar articles and updates, feel free to explore my Medium profile:

Join me as we explore the exciting world of tech, data and beyond!

What did you think about this article? Let me know in the comments below … or above, depending on your device! 🙃

Please consider supporting me by:

  1. Clapping 50 times for this story.
  2. Leaving a comment telling me your thoughts.
  3. Highlighting your favorite part of the story.
  4. Connect with me on LinkedIn
  5. Connect with me on Twitter

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

CyCoderX
CyCoderX

Written by CyCoderX

Machine Learning & Data Engineer | Data Science | Python & SQL | AI | Software Developer | Azure & AWS Cloud Specialist | Blogger simplifying Big Data & Trends

Python in Plain English
Python in Plain English

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.