Explain __init__() and __str__() methods with examples. Discuss type-based dispatch in Python
Answer:-
__init__()
Method
__init__
is a special method used to initialize object attributes.- It is called automatically when a new object is created.
Example (from 17.5):
class Time: def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second
Usage:
time = Time(9, 45)
This sets time.hour = 9
, time.minute = 45
, and time.second = 0
.
__str__()
Method
__str__
is used to define the string representation of an object.- It is called automatically by the
print()
function.
Example (from 17.6):
class Time: def __str__(self): return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
Usage:
time = Time(9, 45) print(time) # Output: 09:45:00
Type-Based Dispatch
- A method uses
isinstance()
to behave differently based on the type of argument passed. - Useful in operator overloading or when an operation depends on operand type.
Example (from 17.8):
def __add__(self, other): if isinstance(other, Time): return self.add_time(other) else: return self.increment(other)
Usage:
start = Time(9, 45) duration = Time(1, 35) print(start + duration) # Time + Time print(start + 1337) # Time + int
This allows the same +
operator to work with both Time
and int
types by dispatching based on the argument type.