วันอาทิตย์ที่ 18 กุมภาพันธ์ พ.ศ. 2567

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

 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.
  • 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, CallableClass has a __call__ method that increments a counter each time the instance is called. The instance obj is callable, and calling it modifies the counter and returns a message.


ไม่มีความคิดเห็น:

แสดงความคิดเห็น

How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be employed to mitigate its effects?

  Q10: How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be emplo...