Object-Oriented Programming in Python
Tags: python, programming, beginners, productivity
Published: 2023-07-27 03:51:15

<p data-pm-slice="1 3 []">Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects." These objects are instances of classes, which act as blueprints or templates defining the structure and behavior of the objects. Python, being an object-oriented language, embraces OOP principles, allowing developers to create modular and reusable code by organizing it into classes and objects.</p>
Let's delve deeper into the core concepts of Object-Oriented Programming in Python:
<h2>Classes and Objects:</h2>
In Python, everything is an object, and objects are instances of classes. Classes define the blueprint for creating objects with their attributes (variables) and methods (functions). Let's start by creating a simple class called Person:
```python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

```
<strong>Explanation:</strong>

The Person class has an <strong>init</strong> method, which serves as the constructor and is called when creating a new class object.
The self parameter refers to the instance of the object being created and allows us to access its attributes.
The greet method is a simple function that prints a greeting message using the object's attributes.
<h2>Creating Objects:</h2>
Once a class is defined, we can create objects (instances) of that class. Let's create two Person objects and invoke the greet method:
```python
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

person1.greet()
person2.greet()

```
<strong>Output:</strong>
```python
Hello, my name is Alice and I'm 25 years old.
Hello, my name is Bob and I'm 30 years old.

```
<strong>Explanation:</strong>

We create two Person objects, person1 and person2, by calling the class as if it were a function with the desired arguments.
We can then invoke the greet method on each object, which prints the respective greeting message.
<h2>Class Attributes and Methods:</h2>
In addition to instance attributes and methods, classes can have attributes and methods shared by all class instances. These are called class attributes and methods. Let's add a class attribute to our Person class:
```python
class Person:
    count = 0  # Class attribute

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Person.count += 1

    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

print(Person.count)  # Output: 0
person1 = Person("Alice", 25)
print(Person.count)  # Output: 1
person2 = Person("Bob", 30)
print(Person.count)  # Output: 2

```
<strong>Explanation:</strong>

We added a class attribute called count to keep track of the number of Person objects created.
The <strong>init</strong> method increments the count attribute whenever a new object is created.
By accessing Person.count, we can see the count value before and after creating the objects.
<h2>Inheritance:</h2>
One of the key features of object-oriented programming is inheritance, which allows a class to inherit attributes and methods from another class. Let's demonstrate inheritance with an example:
```python
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

    def study(self):
        print(f"{self.name} is studying hard for grade {self.grade}.")

```
<strong>Explanation:</strong>

The Student class is defined as a subclass of the Person class by specifying it in parentheses after the class name.
The super().<strong>init</strong>(name, age) line calls the parent class's <strong>init</strong> method to initialize the inherited attributes.
The study method is specific to the Student class and prints a study message using the student's name and grade.
<h2>Creating and Using a Subclass:</h2>
Now, let's create a Student object and invoke both inherited and subclass-specific methods:
```python
student1 = Student("Emma", 18, 12)

student1.greet()
student1.study()

</code></pre>
<strong>Output:</strong>
<pre><code class="language-javascript">Hello, my name is Emma and I'm 18 years old.
Emma is studying hard for grade 12.

```
<strong>Explanation:</strong>

We create a Student object, student1, and provide the necessary arguments for the Person and Student class constructors.
We can invoke the inherited greet method from the Person class and the subclass-specific study method.
<h3><strong>Polymorphism</strong></h3>
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables using a single interface to represent different types of objects, making the code more flexible and extensible.
```python
class Cat:
    def make_sound(self):
        return "Meow!"

class Cow:
    def make_sound(self):
        return "Moo!"

# Polymorphic function that works with both Cat and Cow objects
def animal_sound(animal):
    return animal.make_sound()

cat = Cat()
cow = Cow()
print(animal_sound(cat))  # Output: Meow!
print(animal_sound(cow))  # Output: Moo!
```
<h3><strong>Encapsulatio</strong>n</h3>
Encapsulation is the principle of restricting access to certain class components, usually achieved by using private attributes or methods. This prevents external interference and enhances data security and integrity.
```python
class BankAccount:
    def __init__(self, account_number, balance):
        self.__account_number = account_number
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount &lt;= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient funds.")

    def get_balance(self):
        return self.__balance

# Accessing private attributes via methods
account = BankAccount("123456789", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())  # Output: 1300
```
<h2>Conclusion:</h2>
Object-oriented programming is a fundamental concept in Python that provides a structured and efficient approach to code organization. You can create reusable code by leveraging classes and objects, encapsulate data and behavior, and achieve more modular and maintainable programs.

This beginner's guide has introduced you to the basics of object-oriented programming in Python, including classes, objects, instance attributes, methods, class attributes, and inheritance.

Remember, the examples provided here are just the tip of the iceberg. Object-oriented programming offers many more advanced concepts and techniques to explore, such as polymorphism, encapsulation, and abstraction. So, keep practicing and diving deeper into the world of OOP with Python!

This was culled from <a class="crayons-link fw-bold" href="https://dev.to/jvertt" target="_blank" rel="noopener noreferrer nofollow">Justin Verthein</a> and Edited by <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Leaernhub Blog</a>.
<h3>Resource</h3>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/06/13-powerful-python-snippets-to-automate-tasks/" target="_blank" rel="noopener noreferrer nofollow">13 Powerful Python Snippets To Automate Tasks</a></li>
 	<li><a class="attrlink" href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
</ul>