Python Programming - Question 18 Answers
Q18 (a): Discuss about Memory Management in Python.
Python handles memory management automatically using the following mechanisms:
1. Automatic Garbage Collection:
- Python uses a built-in garbage collector to manage memory.
- It reclaims memory from objects that are no longer in use using reference counting and cyclic
garbage collection.
2. Reference Counting:
- Each object in Python has a reference count.
- When the count drops to zero (i.e., no references), the memory is freed.
3. Private Heap:
- All Python objects and data structures are stored in a private heap.
- This memory is inaccessible to the programmer directly but managed by the Python interpreter.
4. Memory Pooling:
- Python uses a memory manager and allocates memory in blocks (pools).
- This optimizes memory use and improves performance.
5. Dynamic Typing:
- Memory is allocated at runtime depending on the object type and size.
6. Modules Involved:
- 'gc': Controls the garbage collector.
- 'sys': Offers access to reference count through sys.getrefcount().
Example:
import gc
gc.collect() # Manually triggers garbage collection
Q18 (b): Explain the concepts of Operator Overloading in Python. Give an Example.
Operator Overloading allows the same operator to have different meanings based on the operands.
In Python, this is achieved by defining special methods in a class, such as:
- __add__ for +
- __sub__ for -
- __mul__ for *
- __eq__ for ==, etc.
Example:
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)
def __str__(self):
return f"({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # Output: (4, 6)
Here, the '+' operator is overloaded to add two Point objects using the __add__ method.