Object-Oriented Programming (OOP) in Python revolves around creating objects that encapsulate data and behavior. Below are 10 key OOP concepts in Python, explained with simple examples.
1. Class
A class is a blueprint for creating objects.
class Dog:
def bark(self):
print("Woof!")
# Creating an object
my_dog = Dog()
my_dog.bark() # Output: Woof!
2. Object
An object is an instance of a class.
class Car:
def __init__(self, brand):
self.brand = brand
car1 = Car("Toyota")
print(car1.brand) # Output: Toyota
3. Encapsulation
Encapsulation is bundling data and methods that operate on the data within one unit.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
4. Abstraction
Abstraction hides complex implementation details and shows only the essential features.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Bark")
dog = Dog()
dog.make_sound() # Output: Bark
5. Inheritance
Inheritance allows a class to inherit properties and methods from another class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.speak() # Output: Animal speaks
d.bark() # Output: Dog barks
6. Polymorphism
Polymorphism allows methods to do different things based on the object calling them.
class Bird:
def sound(self):
print("Some bird sound")
class Sparrow(Bird):
def sound(self):
print("Chirp")
class Parrot(Bird):
def sound(self):
print("Squawk")
for bird in [Sparrow(), Parrot()]:
bird.sound()
# Output:
# Chirp
# Squawk
7. Constructor (__init__
Method)
The __init__
method is a special method that gets called when an object is created.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s = Student("Alice", 21)
print(s.name, s.age) # Output: Alice 21
8. Destructor (__del__
Method)
The __del__
method is called when an object is deleted.
class File:
def __init__(self, name):
self.name = name
print(f"File {self.name} opened")
def __del__(self):
print(f"File {self.name} closed")
f = File("test.txt")
del f
# Output:
# File test.txt opened
# File test.txt closed
9. Method Overriding
Overriding allows a subclass to provide a specific implementation of a method defined in a parent class.
class Shape:
def area(self):
return 0
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
c = Circle(5)
print(c.area()) # Output: 78.5
10. Class and Static Methods
- Class methods take the class as their first argument.
- Static methods don’t take the class or instance as an argument.
class Math:
count = 0
@classmethod
def increment_count(cls):
cls.count += 1
@staticmethod
def add(a, b):
return a + b
Math.increment_count()
print(Math.count) # Output: 1
print(Math.add(5, 3)) # Output: 8
Test your understanding
1. What is the purpose of a class in Python?
A. To store data only
B. To define a blueprint for creating objects
C. To execute functions
D. To manage memory allocation
Explanation: A class defines a blueprint for creating objects with attributes and methods.
2. Which of the following is used to create an object in Python?
A. object()
B. create()
C. ClassName()
D. new()
Explanation: An object is created by calling the class as if it were a function, like my_obj = MyClass()
.
3. What does encapsulation mean in OOP?
A. Inheriting from another class
B. Hiding the complexity from the user
C. Wrapping data and methods in a single unit
D. Creating multiple objects
Explanation: Encapsulation binds data and functions that operate on the data into one unit (class).
4. Which method is used to hide the internal implementation and show only necessary details?
A. Encapsulation
B. Inheritance
C. Abstraction
D. Polymorphism
Explanation: Abstraction hides implementation details and only exposes relevant information.
5. What does the __init__
method do in a class?
A. Destroys the object
B. Initializes the class method
C. Initializes the object attributes
D. Returns the class object
Explanation: __init__
is a constructor that initializes the attributes when an object is created.
6. What is inheritance used for in OOP?
A. To hide data from other classes
B. To create private variables
C. To reuse code from another class
D. To overload operators
Explanation: Inheritance allows a class to reuse the properties and methods of another class.
7. What is method overriding in Python?
A. Using the same method name in the same class
B. Defining the same method in the parent and child classes, with different behavior
C. Calling multiple methods with one name
D. Rewriting Python built-in functions
Explanation: Method overriding lets a subclass provide a specific implementation of a method already defined in the superclass.
8. What is the output of the following code?
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
obj = B()
obj.show()
A. A
B. B
C. Error
D. None
Explanation: B
overrides the show()
method of class A
, so “B” is printed.
9. Which method is automatically called when an object is deleted in Python?
A. __init__
B. __del__
C. destroy()
D. __delete__
Explanation: __del__
is the destructor method that is automatically called when an object is deleted.
10. What is the difference between a class method and a static method in Python?
A. Class methods use self
, static methods use cls
B. Class methods require an object
C. Class methods use cls
and can modify class state, static methods do not access class or instance data
D. There is no difference
Explanation: Class methods receive the class as the first argument (cls
), static methods do not take any special first argument and cannot access or modify class or instance state.