top of page
Writer's pictureRevanth Reddy Tondapu

Part 22: Dive into the World of OOP in Python: Classes, Inheritance, and More!


OOP in Python
OOP in Python

Hello, future coders! Welcome to an exciting journey into Object-Oriented Programming (OOP) in Python. Today, we'll be exploring some fundamental concepts that will make your coding experience more structured and fun. So, let’s get started!


What is a Class?

Imagine a class as a blueprint for creating objects, which can be anything from cars to animals. This blueprint defines the properties (attributes) and behaviors (methods) that the objects created from the class will have.

For example, think of a car. A car has attributes like windows, doors, and engine type. It also has behaviors like driving and honking. In Python, we can represent this car using a class.


Creating a Simple Class in Python

Let's start by creating a simple class for a car.

Step 1: Define the Class

To define a class in Python, we use the class keyword followed by the class name.

class Car:
    pass

Here, Car is a class, and pass means we haven't added any properties or methods yet.


Step 2: Add Attributes and Methods

Now, let's add some attributes and methods to our Car class. We’ll use the init method, also known as the constructor, to initialize the attributes.

class Car:
    def __init__(self, windows, doors, engine_type):
        self.windows = windows
        self.doors = doors
        self.engine_type = engine_type

    def describe(self):
        return f"This car has {self.windows} windows, {self.doors} doors, and runs on {self.engine_type}."

In this example:

  • init initializes the attributes windows, doors, and engine_type.

  • describe is a method that returns a description of the car.


Step 3: Create Objects from the Class

Now, let’s create instances (objects) from our Car class.

# Creating car objects
car1 = Car(4, 5, "petrol")
car2 = Car(3, 3, "diesel")

# Using the describe method
print(car1.describe())
print(car2.describe())

When you run this code, you'll see:

This car has 4 windows, 5 doors, and runs on petrol.
This car has 3 windows, 3 doors, and runs on diesel.

Understanding Inheritance

Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). This helps in reusing code and creating a hierarchical relationship between classes.

Example: Creating a SportsCar Class

Let's create a SportsCar class that inherits from the Car class.

class SportsCar(Car):
    def __init__(self, windows, doors, engine_type, top_speed):
        super().__init__(windows, doors, engine_type)
        self.top_speed = top_speed

    def describe(self):
        return super().describe() + f It can go up to {self.top_speed} km/h."

In this example:

  • SportsCar inherits from Car.

  • super().__init__ calls the constructor of the Car class to initialize the inherited attributes.

  • We also add a new attribute top_speed and extend the describe method.


Creating SportsCar Objects

# Creating a sports car object
sports_car = SportsCar(2, 2, "petrol", 300)

# Using the describe method
print(sports_car.describe())

When you run this code, you'll see:

This car has 2 windows, 2 doors, and runs on petrol. It can go up to 300 km/h.

Encapsulation and Data Abstraction

Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on the data into a single unit (class). It also restricts access to some of the object's components, which is useful for data abstraction.

Private, Protected, and Public Variables

In Python:

  • Public variables are accessible from anywhere.

  • Protected variables (prefix with _) are intended to be accessed within the class and its subclasses.

  • Private variables (prefix with __) are intended to be accessed only within the class.


Example: Encapsulation in Python

class Car:
    def __init__(self, windows, doors, engine_type):
        self.windows = windows  # Public
        self._doors = doors     # Protected
        self.__engine_type = engine_type  # Private

    def describe(self):
        return f"This car has {self.windows} windows, {self._doors} doors, and runs on {self.__engine_type}."

In this example:

  • windows is a public attribute.

  • _doors is a protected attribute.

  • __engine_type is a private attribute.


Accessing Attributes

car = Car(4, 5, "petrol")
print(car.windows)  # Accessible
print(car._doors)   # Accessible, but should be treated as protected
print(car.__engine_type)  # Not directly accessible

To access the private attribute, you can use a method within the class.

class Car:
    def __init__(self, windows, doors, engine_type):
        self.windows = windows
        self._doors = doors
        self.__engine_type = engine_type

    def get_engine_type(self):
        return self.__engine_type

Now you can access the private attribute through the method.

car = Car(4, 5, "petrol")
print(car.get_engine_type())  # Accessible through method

Conclusion

Today, we explored the basics of OOP in Python, including classes, inheritance, encapsulation, and data abstraction. Understanding these concepts will help you write more organized and reusable code.

In our next post, we'll dive deeper into other OOP concepts like polymorphism and advanced inheritance techniques. Stay tuned, keep coding, and have fun!

Happy coding!

3 views0 comments

Recent Posts

See All

Comments


bottom of page