Introduction to Object-Oriented Programming (OOP) in Python

Introduction to Object-Oriented Programming (OOP) in Python

In this tutorial, we'll explore the basics of Object-Oriented Programming (OOP) using Python. OOP is a programming paradigm that uses "objects" to represent data and methods that operate on that data.

Simple Example: A Basic Class

Let's start with a simple class that represents a Dog. This class will have attributes like name and age, and a method to display the dog's details.

# Define a simple class
class Dog:
    # Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # Method to display dog details
    def display(self):
        print(f"Dog: {self.name}, Age: {self.age}")
        
# Creating an object of the class
dog1 = Dog("Buddy", 4)
dog1.display()

Understanding Classes

A class is a blueprint for creating objects. It defines a set of attributes that will characterize any object that is instantiated from the class. Attributes are defined in the class body, and they can be data attributes (variables) or methods (functions).

# Define a more detailed class
class ShoppingItem:
    # Constructor
    def __init__(self, name, quantity):
        self.name = name
        self.quantity = quantity
    
    # Method to display item details
    def display(self):
        print(f"Item: {self.name}, Quantity: {self.quantity}")
        
# Creating an object of the class
item1 = ShoppingItem("Apple", 3)
item1.display()

Methods in Classes

Methods are functions defined inside a class that describe the behaviors of the objects. In our ShoppingItem class, we have defined a method display to print the details of the shopping item.

# Create more objects
item2 = ShoppingItem("Banana", 5)
item3 = ShoppingItem("Orange", 2)

# Display the details of each item
item2.display()
item3.display()

Creating an Array of Objects

Now, let's create a list (array) of ShoppingItem objects. We will prompt the user to input different items and their quantities. The user can type "finished" when they are done adding items.

# Initialize an empty list to hold shopping items
shopping_list = []

while True:
    name = input("Enter item name (or 'finished' to end): ")
    if name.lower() == 'finished':
        break
    quantity = int(input("Enter quantity: "))
    item = ShoppingItem(name, quantity)
    shopping_list.append(item)

# Display all items in the shopping list
for item in shopping_list:
    item.display()

Inheritance in OOP

Inheritance allows a class to inherit attributes and methods from another class. This helps in reusing code and building a hierarchy of classes. Let's create a PerishableItem class that inherits from ShoppingItem and adds an expiry date.

# Define a class that inherits from ShoppingItem
class PerishableItem(ShoppingItem):
    def __init__(self, name, quantity, expiry_date):
        super().__init__(name, quantity)  # Call the constructor of the parent class
        self.expiry_date = expiry_date
    
    # Method to display item details with expiry date
    def display(self):
        print(f"Item: {self.name}, Quantity: {self.quantity}, Expiry Date: {self.expiry_date}")

# Creating an object of the derived class
item4 = PerishableItem("Milk", 2, "2024-07-01")
item4.display()

Benefits of OOP

1. Encapsulation: OOP allows bundling of data and methods that operate on that data within a single unit called a class.
2. Inheritance: It enables new classes to inherit features from existing classes, promoting code reuse.
3. Polymorphism: OOP allows methods to do different things based on the object it is acting upon, making the code more flexible and reusable.
4. Abstraction: OOP enables hiding complex implementation details and showing only the essential features of the object, simplifying code management.

Resources

Summary

In this tutorial, we've covered the basics of Object-Oriented Programming (OOP) in Python. We learned about classes, methods, creating objects, inheritance, and the benefits of OOP. By understanding these concepts, you can write more organized, reusable, and scalable code.