Python OOP


Python supports Object-Oriented Programming (OOP) which lets you structure code using classes and objects.


🔹 Class & Object

A class is a blueprint.
An object is an instance of the class.

class Car:
    def __init__(self, brand):
        self.brand = brand

mycar = Car("Tesla")
print(mycar.brand)  # Tesla

🔹 __init__() Constructor

The __init__() method runs automatically when the object is created.

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

🔹 self Keyword

self refers to the current instance of the class.


🔹 Object Methods

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

    def greet(self):
        print("Hi, " + self.name)

s1 = Student("Amit")
s1.greet()  # Hi, Amit

🔹 Modify Object Property

s1.name = "Ravi"
print(s1.name)

🔹 Delete Object or Property

del s1.name
del s1

🔹 Inheritance

A class can inherit from another class.

class Animal:
    def speak(self):
        print("Sound")

class Dog(Animal):
    def bark(self):
        print("Woof")

d = Dog()
d.speak()  # Sound
d.bark()   # Woof

🔹 Super() Function

Use super() to call the parent class's constructor.

class Animal:
    def __init__(self):
        print("Animal created")

class Dog(Animal):
    def __init__(self):
        super().__init__()
        print("Dog created")

🔹 Encapsulation

Hide internal details using private attributes:

class Account:
    def __init__(self):
        self.__balance = 1000  # private

a = Account()
# print(a.__balance)  # Error

🔹 Polymorphism

Different classes can define the same method differently.

class Bird:
    def sound(self):
        print("Tweet")

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

Practice Questions

Q1. Write a Python program to create a Book class with attributes title and author.

Q2. Write a Python program to add a method display() in the Book class to show book information.

Q3. Write a Python program to create multiple objects of the Book class and call the display() method for each.

Q4. Write a Python program to create a base class Employee and a derived class Manager that inherits from Employee.

Q5. Write a Python program to use super() in the Manager class to call the parent constructor.

Q6. Write a Python program to add a private variable in a class (using __var) and restrict direct access from outside the class.

Q7. Write a Python program to implement a sound() method in two different classes (e.g., Dog, Cat) and use polymorphism to call them.

Q8. Write a Python program to change the value of an object property after the object has been created.

Q9. Write a Python program to delete a property of an object using del.

Q10. Write a Python program to create a class with both class-level and object-level attributes, and print both.


Go Back Top