OOPs Concepts for Assessment Test (Python)
Object-Oriented Programming (OOP) Concepts in Python
1. Introduction to OOP
Object-Oriented Programming is a paradigm based on the concept of "objects", which contain data
and methods.
2. Basic Concepts of OOP
a. Class and Object
- **Class**: Blueprint for creating objects.
- **Object**: Instance of a class.
```python
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
d = Dog("Buddy")
print(d.bark())
```
b. Encapsulation
- Wrapping data and methods in a single unit (class).
- Hides internal state and requires all interaction to be performed through an object's methods.
```python
class Account:
def __init__(self):
self.__balance = 0 # private variable
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
```
c. Inheritance
- One class can inherit attributes and methods from another class.
```python
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self):
return "Dog barks"
d = Dog()
print(d.speak()) # Output: Dog barks
```
d. Polymorphism
- Same function name with different implementations.
```python
class Bird:
def fly(self):
print("Some birds can fly")
class Penguin(Bird):
def fly(self):
print("Penguins can't fly")
def flying_test(bird):
bird.fly()
flying_test(Bird())
flying_test(Penguin())
```
e. Abstraction
- Hiding the complex implementation and showing only essentials.
```python
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
c = Car()
c.start()
```
3. Advanced OOP Concepts
a. Constructors and Destructors
```python
class Demo:
def __init__(self):
print("Constructor called")
def __del__(self):
print("Destructor called")
```
b. Class and Static Methods
```python
class MyClass:
count = 0
@classmethod
def increment(cls):
cls.count += 1
@staticmethod
def greet():
print("Hello!")
```
c. Operator Overloading
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
```
4. MCQs and Output-Based Questions
1. What is encapsulation in Python?
a) Inheriting methods from a class
b) Hiding the internal state of an object
c) Overloading operators
d) Writing multiple methods with the same name
2. Output?
```python
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
obj = B()
obj.show()
```
a) A
b) B
c) AB
d) Error
Answer: b) B