top of page

Object-Oriented Programming in Python

Object-oriented programming (OOP) is a powerful programming paradigm that allows you to structure your code around objects, which are instances of classes. In this lesson, we will explore the fundamentals of object-oriented programming using Python.

1. Classes and Objects: In Python, a class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects of that class will have. Here's an example:

In the above code, we define a Car class with attributes make and model using the __init__ method (a special method used to initialize objects). We also define a drive method that prints a message.

2. Creating Objects: Once we have a class, we can create objects (instances) of that class. Here's how we can create instances of the Car class:

Screenshot 2023-06-01 at 8.54_edited.jpg

3. Accessing Attributes and Methods: We can access the attributes and methods of an object using the dot notation (object.attribute or object.method()). Here are a few examples:

​

Screenshot 2023-06-01 at 9.07_edited.jpg

4. Inheritance: One of the key features of OOP is inheritance, which allows us to create a new class (derived class) based on an existing class (base class). The derived class inherits the attributes and methods of the base class and can add its own as well. Here's an example:

Screenshot 2023-06-01 at 9.45_edited.jpg

In the above code, we define an ElectricCar class that inherits from the Car class. It adds a new attribute range and a new method charge. We use the super() function to call the base class's __init__ method to initialize the inherited attributes.

5. Polymorphism: Polymorphism allows objects of different classes to be used interchangeably if they have a common interface. It enables code reuse and flexibility. Here's an example:

Screenshot 2023-06-01 at 10.13_edited.jp

In the above code, the perform_drive function takes a car object as an argument and calls its drive method. We can pass both a Car object and an ElectricCar object, demonstrating polymorphism.

Conclusion: Object-oriented programming provides a structured way to design and organize code. By using classes and objects, you can create reusable and modular code. Python's support for OOP makes it a versatile language for building complex applications.

bottom of page