Python
Course Index
Index

Python OOP

1. What is Object-Oriented Programming (OOP)?

OOP is a programming paradigm that organizes code using objects and classes to promote modularity, reusability, and organization.

2. What are the four pillars of OOP?

  • Encapsulation : Hiding internal details and exposing only necessary functionality.
  • Abstraction : Hiding implementation details and exposing only relevant features.
  • Inheritance : Acquiring properties and behaviors from a parent class.
  • Polymorphism : Using the same method or function with different implementations.

3. What is a class in Python?

A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions).
Example:

Python
Copy
class Car:
    def __init__(self, brand, model):
        self.brand = brand  # Attribute
        self.model = model

    def display_info(self):  # Method
        print(f"Car: {self.brand} {self.model}")

# Creating an object
my_car = Car("Toyota", "Camry")
my_car.display_info()  # Output: Car: Toyota Camry

4. What is an object in Python?

An object is an instance of a class. It has its own attributes (data) and can perform methods (functions).
Example:

Javascript
Copy
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

dog1 = Dog("Buddy", "Labrador")  # Creating an object
print(dog1.name)  # Output: Buddy

5. What is the difference between a class and an instance?

Feature Class Instance (Object)
Definition Blueprint for creating objects Actual object created from a class
Memory Allocation No memory allocated for data Memory is allocated for each object
Example Car (general blueprint) my_car = Car("Toyota", "Camry")

5. What is the self keyword in Python?

  • self refers to the current instance of the class.
  • It is used to access instance variables and methods.
Example:
Python
Copy
class Person:
    def __init__(self, name):
        self.name = name  # self refers to the instance

    def greet(self):
        print(f"Hello, my name is {self.name}")

p = Person("Alice")
p.greet()  # Output: Hello, my name is Alice

7. What is the __init__() method?

  • It is the constructor in Python.
  • It gets called automatically when an object is created.
Example:
Python
Copy
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

s = Student("John", 20)
print(s.name, s.age)  # Output: John 20

8. What is encapsulation in Python?

  • Encapsulation is the concept of restricting access to certain details of an object.
  • In Python, we use private (__var) and protected (_var) variables to achieve encapsulation.
Example:
Python
Copy
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable

    def get_balance(self):
        return self.__balance  # Accessing private variable

acc = BankAccount(1000)
print(acc.get_balance())  # Output: 1000
print(acc.__balance)  # AttributeError: Cannot access private variable

9. What is abstraction in Python?

  • Abstraction hides unnecessary implementation details from the user.
  • Implemented using abstract classes (via ABC module).
Example:
Python
Copy
from abc import ABC, abstractmethod

class Animal(ABC):  # Abstract class
    @abstractmethod
    def make_sound(self):
        pass  # Abstract method

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

dog = Dog()
dog.make_sound()  # Output: Woof! Woof!

10. What is inheritance in Python?

Inheritance allows a class (child) to derive attributes and methods from another class (parent). Example:

Python
Copy
class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):  # Dog inherits from Animal
    def speak(self):
        print("Dog barks")

d = Dog()
d.speak()  # Output: Dog barks

11. What is multiple inheritance in Python?

Multiple Inheritance allows a child class to inherit from more than one parent class. Example:

Python
Copy
class A:
    def method_A(self):
        print("Method A")

class B:
    def method_B(self):
        print("Method B")

class C(A, B):
    pass

c = C()
c.method_A()  # Output: Method A
c.method_B()  # Output: Method B

12. What is polymorphism in Python?

Polymorphism allows methods in different classes to have the same name but different implementations. Example:

Python
Copy
class Bird:
    def speak(self):
        print("Bird chirps")

class Dog:
    def speak(self):
        print("Dog barks")

def animal_speak(animal):
    animal.speak()

bird = Bird()
dog = Dog()
animal_speak(bird)  # Output: Bird chirps
animal_speak(dog)  # Output: Dog barks

13. What are class methods and static methods?

Feature Class Method (@classmethod) Static Method (@staticmethod)
Accesses Class-level attributes Neither class nor instance attributes
Uses cls? Yes No
Uses self? No No
Example:
Python
Copy
class Example:
    class_var = "I am class variable"

    @classmethod
    def class_method(cls):
        print(f"Class method: {cls.class_var}")

    @staticmethod
    def static_method():
        print("Static method: No access to class variables")

Example.class_method()  # Output: Class method: I am class variable
Example.static_method()  # Output: Static method: No access to class variables

14. What is operator overloading?

Operator overloading allows defining custom behavior for operators like +, -, *, etc.
Example:

Python
Copy
class Point:
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        return Point(self.x + other.x)

p1 = Point(10)
p2 = Point(20)
p3 = p1 + p2  # Calls __add__()
print(p3.x)  # Output: 30

15. What is a data class in Python?

Data classes automatically generate methods like __init__(), __repr__(), and __eq__().
Example:

Python
Copy
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

p = Person("Alice", 30)
print(p)  # Output: Person(name='Alice', age=30)