+91 9873530045
admin@learnwithfrahimcom
Mon - Sat : 09 AM - 09 PM

Day 6.1 : Object-Oriented Programming (OOP) in Python


Step 1: Classes and Objects

Classes are blueprints; objects are instances of classes.

# Defining a class
class Student:
  pass # empty class

# Creating an object
s1 = Student()
print(type(s1))

Explanation: Student is a class; s1 is an object (instance).

Step 2: __init__ method and attributes

Use __init__ to initialize object attributes.

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

s1 = Student("Alisha", 30)
print(s1.name, s1.age)

Explanation: self refers to the object itself. Attributes store object-specific data.

Step 3: Methods

Methods are functions inside classes that act on objects.

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

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

s1 = Student("Alisha", 30)
s1.greet()

Explanation: Methods access object attributes using self. Here, greet() prints a personalized message.

Step 4: Inheritance

Inheritance allows one class to use properties of another.

class Person:
  def __init__(self, name):
    self.name = name

class Student(Person):
  def greet(self):
    print(f"Hello, I am {self.name}!")

s1 = Student("Alisha")
s1.greet()

Explanation: Student inherits from Person and can access its attributes.

Step 5: Encapsulation

Private attributes are not directly accessible outside the class.

class Student:
  def __init__(self, name, grade):
    self.__grade = grade # private attribute
    self.name = name

  def get_grade(self):
    return self.__grade

s1 = Student("Alisha", "A")
print(s1.name)
print(s1.get_grade()) # Access private attribute via method

Explanation: Use double underscore __ to make attributes private. Access them via getter/setter methods.

Step 6: Polymorphism

Polymorphism allows different classes to use the same method name differently.

class Cat:
  def sound(self):
    print("Meow")

class Dog:
  def sound(self):
    print("Woof")

def make_sound(animal):
  animal.sound()

c = Cat()
d = Dog()
make_sound(c)
make_sound(d)

Explanation: Both Cat and Dog have sound(), but behavior depends on object type.

Step 7: PyCharm Project Layout

OOPProject
├── student.py
├── inheritance_demo.py
├── encapsulation_demo.py
└── polymorphism_demo.py
# Example: student.py
class Student:
  def __init__(self, name, grade):
    self.name = name
    self.grade = grade

s1 = Student("Alisha", "A")
print(s1.name, s1.grade)

Step 8: Tips & Best Practices

  • Use classes to group related data and functions.
  • Keep attributes private when necessary and use getters/setters.
  • Use inheritance to avoid code duplication.
  • Use polymorphism for flexible code design.
  • Follow proper naming conventions for classes and methods.
✔ End of Day 6 – You now understand Object-Oriented Programming in Python, including classes,