List and explain any four object-oriented characteristics possessed by Python

Python is an object-oriented programming language that supports the key principles of object-oriented design. These characteristics help in creating modular, reusable, and structured code. The four main object-oriented characteristics possessed by Python are:


1. Encapsulation

Encapsulation is the process of bundling data (attributes) and methods (functions) that operate on the data into a single unit called a class. It restricts direct access to some of the object’s components, which helps in preventing accidental modification.

Example:

class Rectangle:
    """Represents a rectangle."""
    def __init__(self, width, height):
        self.width = width
        self.height = height

Here, width and height are encapsulated inside the Rectangle class.

Encapsulation helps in protecting internal object state and hides unnecessary details from the user.


2. Inheritance

Inheritance allows a class (child class) to acquire properties and behavior (methods) from another class (parent class). This promotes code reusability and establishes a relationship between different classes.

Python allows inheritance by simply passing the parent class as a parameter to the child class.

Example:

class Animal:
    def sound(self):
        print("Animal sound")

class Dog(Animal):
    def sound(self):
        print("Bark")

The Dog class inherits from Animal and overrides the sound method.


3. Polymorphism

Polymorphism means “many forms”. It allows the same operation to behave differently on different classes. It is commonly implemented using method overriding or operator overloading.

Example (operator overloading from 17.7):

class Time:
    def __add__(self, other):
        seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)

This allows + to work with Time objects, behaving according to how __add__() is defined.


4. Abstraction

Abstraction means hiding internal details and showing only the relevant features of an object. It simplifies complexity by exposing only the necessary parts of an object.

Python supports abstraction using classes and methods. Internal computations are hidden behind method calls.

Example:

class Time:
    def time_to_int(self):
        minutes = self.hour * 60 + self.minute
        seconds = minutes * 60 + self.second
        return seconds

Users do not need to know how time is converted; they just call time_to_int().


Conclusion

Python supports all the major object-oriented characteristics:

  • Encapsulation allows secure code organization.
  • Inheritance promotes reuse and hierarchy.
  • Polymorphism allows flexibility with function/operator usage.
  • Abstraction hides complexity and improves usability.

Leave a Reply

Your email address will not be published. Required fields are marked *