DEV Community

Romulo Gatto
Romulo Gatto

Posted on

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) in Python

Welcome to the world of object-oriented programming in Python! In this guide, we'll explore the basics of OOP and how it can help you write efficient, modular, and reusable code.

What is Object-Oriented Programming?

Object-Oriented Programming is a programming paradigm that revolves around objects. An "object" represents a specific instance of a class - which acts as a blueprint for creating objects. Objects have properties (attributes) and behavior (methods), allowing them to interact with other objects.

Compared to procedural programming, where tasks are handled sequentially through functions or procedures, OOP promotes code organization by grouping related data and functionality. This modular approach reduces redundancy and enhances code maintainability.

Classes: The Blueprint for Objects

In Python, classes are defined using the class keyword followed by the class name. Let's create a simple Car class:

class Car:
    def __init__(self, brand):
        self.brand = brand

    def drive(self):
        print(f"The {self.brand} is driving!")
Enter fullscreen mode Exit fullscreen mode

Here we define the Car class with an __init__() method that initializes our car object with its brand attribute. We also define a drive() method that prints out which car brand is being driven.

Creating Objects from Classes

To create an object from our Car class, we simply call the class as if it were a function:

my_car = Car("Tesla")
Enter fullscreen mode Exit fullscreen mode

In this example, we create an instance of our Car class called my_car. We pass "Tesla" as an argument to set the value of its brand attribute during initialization.

Accessing Attributes and Invoking Methods

Once we have an object, we can access its attributes and invoke its methods using the dot notation:

# Output: Tesla
# Output: The Tesla is driving!
Enter fullscreen mode Exit fullscreen mode

my_car.brand accesses the brand attribute of our Car object, while invokes the drive method.

Inheritance: Extending Classes

Inheritance allows us to create new classes that inherit properties and behavior from existing classes. Let's illustrate this with an ElectricCar class that inherits from our base Car class:

class ElectricCar(Car):
    def __init__(self, brand, battery_capacity):
        self.battery_capacity = batter
Enter fullscreen mode Exit fullscreen mode

Top comments (0)