Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

+92 334 341 5471

Programming Python

Object-Oriented Programming with Python: Classes and Objects

Object-Oriented Programming (OOP) is a key paradigm in programming that helps to structure software in a way that is modular, reusable, and easy to maintain. If you’re looking to enhance your programming with Python, learning OOP concepts such as classes and objects is essential. In this article, we’ll explore what classes and objects are, and how you can implement them in Python with practical examples.


Join the conversation! Subscribe to OptimistDev Herald for our take. Click Here


What is Object-Oriented Programming (OOP)?

OOP is a programming paradigm centered around the concept of objects. These objects represent real-world entities, encapsulating data (attributes) and behaviors (methods). OOP emphasizes the following core principles:

  • Encapsulation: Bundling of data and methods that operate on the data into a single unit or class.
  • Inheritance: A mechanism where one class can inherit attributes and methods from another class.
  • Polymorphism: The ability to redefine methods for different classes.
  • Abstraction: Hiding complex implementation details and exposing only the necessary parts.

Now, let’s delve into classes and objects.

Classes in Python

A class is a blueprint for creating objects. It defines the structure and behavior that the objects created from the class will have. In Python, you define a class using the class keyword.

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_info(self):
        return f"Car: {self.year} {self.make} {self.model}"
  • The __init__ method is a special method known as the constructor. It is called automatically when an object is instantiated from the class and is used to initialize the attributes of the object.
  • The self keyword refers to the instance of the class. Every method within a class must have self as its first parameter.
Programming with Python OptimistDev

Objects in Python

An object is an instance of a class. When you create an object from a class, the class’s constructor is called, and memory is allocated for that instance. Let’s create an object from the Car class.

my_car = Car("Toyota", "Corolla", 2021)
print(my_car.display_info())

In the above code, my_car is an object of the Car class. We are passing values for the make, model, and year attributes and then calling the display_info method to display the car’s details.

Output:

Car: 2021 Toyota Corolla

Working with Multiple Objects

You can create multiple objects from the same class, each with its own unique data.

car1 = Car("Honda", "Civic", 2020)
car2 = Car("Ford", "Mustang", 2022)

print(car1.display_info())
print(car2.display_info())

Output:

Car: 2020 Honda Civic
Car: 2022 Ford Mustang

Each object, car1 and car2, contains different data but uses the same methods defined in the Car class.

Methods in Classes

A class can contain various methods that define the behavior of its objects. These methods can interact with the object’s attributes or perform specific tasks.

Let’s add a method to start the car:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.is_running = False

    def start_car(self):
        self.is_running = True
        return f"The {self.year} {self.make} {self.model} has started."

my_car = Car("Toyota", "Corolla", 2021)
print(my_car.start_car())

Output:

The 2021 Toyota Corolla has started.

In this example, the start_car method changes the value of the is_running attribute and returns a message.

Inheritance in Python

Inheritance allows one class (child class) to inherit the attributes and methods of another class (parent class). This helps in code reuse and hierarchical class structures.

class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size):
        super().__init__(make, model, year)
        self.battery_size = battery_size

    def describe_battery(self):
        return f"The {self.year} {self.make} {self.model} has a {self.battery_size}-kWh battery."

Here, the ElectricCar class inherits the attributes and methods of the Car class but also has its own attribute battery_size and a method describe_battery().

my_electric_car = ElectricCar("Tesla", "Model S", 2022, 100)
print(my_electric_car.describe_battery())

Output:

The 2022 Tesla Model S has a 100-kWh battery.

Polymorphism in Python

Polymorphism allows different classes to implement methods that are called in the same way. This means that the same method can behave differently based on the object that is calling it.

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

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

def animal_sound(animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!

Here, both the Dog and Cat classes implement a speak method, but each returns a different output. The function animal_sound demonstrates polymorphism by calling the speak method on different objects without knowing their types.

Conclusion

Object-Oriented Programming (OOP) with Python allows you to design software that is organized, modular, and easy to maintain. The concepts of classes, objects, inheritance, and polymorphism are fundamental to effective programming with Python. With this foundation, you can tackle more complex software development tasks and apply OOP principles to solve real-world problems more efficiently.


Author

Admin herman

Leave a comment

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

Contact Us

Please enable JavaScript in your browser to complete this form.
Name