Python for Beginners begunpro

Python Learning Day 29 & 30: OOP

Python

Welcome to the realm of Object-Oriented Programming (OOP)! Over the next two days, you’ll explore the fundamentals of classes and objects, unlocking a powerful paradigm in Python that enhances code organization and promotes reusability.

Day 29: Understanding Classes and Objects

Classes in Python:

In Python, a class is a blueprint for creating objects. It defines attributes (characteristics) and methods (functions) that the objects will have.

				
					class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} says woof!")

# Creating an instance of the Dog class
my_dog = Dog("Buddy", 3)

# Accessing attributes and calling methods
print(f"{my_dog.name} is {my_dog.age} years old.")
my_dog.bark()

				
			

In this example, Dog is a class with attributes name and age, and a method bark. The __init__ method is a special method called a constructor, which is executed when an object is created.

Objects in Python:

Objects are instances of classes. They encapsulate data (attributes) and behavior (methods).

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

    def start_engine(self):
        print(f"The {self.make} {self.model}'s engine is running.")

# Creating instances of the Car class
my_car = Car("Toyota", "Camry")
your_car = Car("Honda", "Accord")

# Accessing attributes and calling methods
print(f"My car is a {my_car.make} {my_car.model}.")
my_car.start_engine()

print(f"Your car is a {your_car.make} {your_car.model}.")
your_car.start_engine()

				
			

In this example, Car is a class, and my_car and your_car are objects created from this class.

Day 30: Dive Deeper into OOP Concepts

Inheritance:

Inheritance allows a class (subclass/derived class) to inherit attributes and methods from another class (superclass/base class).

				
					class Animal:
    def __init__(self, species):
        self.species = species

    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

class Cat(Animal):
    def make_sound(self):
        print("Meow!")

# Creating instances of the derived classes
my_dog = Dog("Canine")
my_cat = Cat("Feline")

# Calling the overridden method
my_dog.make_sound()
my_cat.make_sound()

				
			

Encapsulation:

Encapsulation restricts access to some components of an object and prevents direct modification. It promotes data hiding and protects the integrity of the object.

				
					class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Single underscore indicates a protected attribute

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

    def withdraw(self, amount):
        if amount <= self._balance:
            self._balance -= amount
        else:
            print("Insufficient funds.")

# Creating an instance of the BankAccount class
account = BankAccount(1000)

# Depositing and withdrawing
account.deposit(500)
account.withdraw(200)

				
			

Exercise: Design Your Own Class

Create a class representing a geometric shape (e.g., circle, rectangle) with relevant attributes and methods. Instantiate objects of this class and demonstrate their functionalities.

Conclusion: Embrace the Power of OOP

Object-Oriented Programming introduces a new level of organization and efficiency to your Python code. As you explore classes, objects, inheritance, and encapsulation, envision how OOP can enhance the structure and maintainability of your projects.

Keep practicing, and get ready for more OOP adventures in the days ahead!

Facebook
Twitter
LinkedIn