Q29: What is the purpose of the __call__ method in Python classes, and how does it allow instances to be callable? Provide an example to illustrate its usage.
A29:
Purpose of
__call__Method:- The
__call__method in Python classes allows instances of a class to be callable as if they were functions. When an object is called as a function, the__call__method is invoked.
- The
Illustration of Usage:
- By defining the
__call__method, a class instance can exhibit behavior similar to a function, making the instance itself callable.
class CallableClass: def __init__(self): self.counter = 0 def __call__(self): self.counter += 1 return f"Instance called. Counter: {self.counter}" # Creating an instance obj = CallableClass() # Calling the instance result1 = obj() result2 = obj() print(result1) print(result2)In this example,
CallableClasshas a__call__method that increments a counter each time the instance is called. The instanceobjis callable, and calling it modifies the counter and returns a message.- By defining the
ไม่มีความคิดเห็น:
แสดงความคิดเห็น