← Back to Dashboard

Object Oriented Programming: Concept Notes

"""
Topic 07: Object Oriented Programming (OOP) - Concept Notes

OOP is a programming paradigm based on the concept of "objects", which can contain data (attributes) and code (methods).

1. Classes and Objects
   - A class is a blueprint for creating objects.
   - An object is an instance of a class.

2. The __init__ Method
   - The constructor method, called when an object is created.
   - Used to initialize attributes.

3. Self
   - Represents the instance of the class. Used to access variables that belong to the class.

4. Pillars of OOP
   - Inheritance: Creating a new class from an existing one (Child inherits from Parent).
   - Encapsulation: Keeping data and methods together and restricting direct access (private attributes).
   - Polymorphism: Different classes can have methods with the same name.
   - Abstraction: Hiding complex implementation details.
"""

# 1. Defining a Class
class Dog:
    species = "Canine" # Class Attribute

    def __init__(self, name, age):
        self.name = name # Instance Attribute
        self.age = age

    def bark(self): # Method
        return f"{self.name} says Woof!"

# 2. Creating an Object
my_dog = Dog("Buddy", 3)
print(my_dog.bark())

# 3. Inheritance
class GoldenRetriever(Dog):
    def fetch(self):
        return f"{self.name} is fetching the ball!"

# 4. Encapsulation (Private)
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance # Private attribute

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
print(f"Balance: {account.get_balance()}")
# print(account.__balance) # This would raise an error