Skip to main content

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming in Python

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. Python is a powerful object-oriented language, and understanding OOP is key to writing reusable, maintainable, and efficient code.

7.1 Classes and Objects

In Python, a class is a blueprint for creating objects (a particular data structure), and an object is an instance of a class. Classes encapsulate data for the object and methods to manipulate that data.

# Example of a class and object in Python

class Car:
    # Constructor
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    
    # Method to display car details
    def display_info(self):
        print(f"Car: {self.year} {self.make} {self.model}")

# Create an object (instance) of the class
my_car = Car("Toyota", "Camry", 2022)
my_car.display_info()

In this example, the Car class has attributes for the car’s make, model, and year. The display_info method prints the car's details. We then create an instance my_car and call the method.

7.2 Inheritance

Inheritance allows one class (child) to inherit attributes and methods from another class (parent). This promotes code reuse and makes it easy to maintain.

# Example of inheritance in Python

class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model
    
    def start(self):
        print(f"{self.make} {self.model} is starting...")

class Car(Vehicle):
    def __init__(self, make, model, year):
        super().__init__(make, model)  # Call the parent class constructor
        self.year = year

    def display_info(self):
        print(f"Car: {self.year} {self.make} {self.model}")

# Create an instance of Car
my_car = Car("Honda", "Civic", 2021)
my_car.start()
my_car.display_info()

In this example, the Car class inherits from the Vehicle class. It uses the parent’s start method and also adds its own method display_info.

7.3 Polymorphism

Polymorphism allows methods to be used interchangeably between different object types. This means that different objects can respond to the same method call in different ways.

# Example of polymorphism in Python

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

# Function that uses polymorphism
def animal_sound(animal):
    print(animal.speak())

# Create instances of Dog and Cat
dog = Dog()
cat = Cat()

# Call the same function on different objects
animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!

In this example, both the Dog and Cat classes have a speak method, but they behave differently. The animal_sound function can handle both types of objects without needing to know their specific class.

7.4 Encapsulation

Encapsulation restricts direct access to some of an object's components, which is a way of preventing accidental modification of data. In Python, encapsulation is achieved by using single or double underscores to indicate "private" or "protected" members.

# Example of encapsulation in Python

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

# Create an instance of BankAccount
account = BankAccount("John", 1000)
account.deposit(500)
print(account.get_balance())  # Output: 1500

# Trying to access a private attribute directly will raise an error
# print(account.__balance)  # This will raise an AttributeError

In this example, the BankAccount class encapsulates the __balance attribute, and it can only be accessed via the get_balance method, not directly.

Comments

Popular posts from this blog

How to Add External Libraries (JAR files) in Eclipse

How to Add External Libraries (JAR files) in Eclipse Adding external libraries (JAR files) to your Eclipse project allows you to use third-party code in your application. This guide will explain what JAR files are, how they differ from `.java` files, where to download them, and how to add them to your project. What are JAR Files? JAR (Java ARchive) files are package files that aggregate many Java class files and associated metadata and resources (such as text, images, etc.) into a single file for distribution. They are used to distribute Java programs and libraries in a platform-independent format, making it easier to share and deploy Java applications. Difference between .java and .jar Files .java files are source files written in the Java programming language. They contain human-readable Java code that developers write. In contrast, .jar files are compile...

Managing Hierarchical Structures: OOP vs Nested Maps in Java

Managing Hierarchical Structures: OOP vs Nested Maps in Java This topic explores the pros and cons of managing hierarchical data using Object-Oriented Programming (OOP) versus nested map structures in Java. This discussion is contextualized with an example involving a chip with multiple cores and sub-cores. Nested Map of Maps Approach Using nested maps to manage hierarchical data can be complex and difficult to maintain. Here’s an example of managing a chip with cores and sub-cores using nested maps: Readability and Maintainability: Nested maps can be hard to read and maintain. The hierarchy is not as apparent as it would be with OOP. Encapsulation: The nested map approach lacks encapsulation, leading to less modular and cohesive code. Error-Prone: Manual management of keys and values increases the risk of errors, such as NullPointerExce...

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration 1. Compiling a C Program to an Executable Step 1: Write a C Program #include <stdio.h> int main() { printf("Hello, World!\\n"); return 0; } Step 2: Compile the C Program gcc -o example example.c 2. Executing the C Program in the Console Step 3: Run the Executable ./example 3. Including Shared .so Libraries Step 4: Create a Shared Library #include <stdio.h> void my_function() { printf("Shared Library Function Called!\\n"); } gcc -shared -o libmylib.so -fPIC mylib.c Step 5: Update the C Program to Use the Shared Library #include <stdio.h> void my_function(); int main() { my_function(); printf("Hello, World!\\n...