Classes and Objects


Object-Oriented Programming is a paradigm that models real-world concepts into code. It involves creating “classes” which act as blueprints for objects , and using those classes to build software.

1. Defining a Class:

A class is like a blueprint for an object. It defines the attributes (data) and methods (functions) that objects of that class will have.

Example: Defining a Class

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

    def bark(self):
        print(self.name + " says Woof!")

2. Creating Objects:

An object is an instance of a class. You create objects using the class blueprint and can customize their attributes.

Example: Creating Objects

# Creating Dog objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

3. Accessing Attributes and Methods:

You can access an object’s attributes and methods using dot notation.

Example: Accessing Attributes and Methods

print(dog1.name)   # Output: Buddy
dog2.bark()        # Output: Max says Woof!

4. Inheritance:

Inheritance lets you create a new class based on an existing one. The new class inherits attributes and methods from the parent class.

Example: Using Inheritance

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

5. Encapsulation and Abstraction:

OOP allows you to hide complex implementation details and provide clear interfaces.

Example: Encapsulation and Abstraction

class BankAccount:
    def __init__(self, balance):
        self._balance = balance   # Protected attribute

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

    def get_balance(self):
        return self._balance

Leave a Reply

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