69. Callable Objects

Here's a collection of 10 Python code snippets to demonstrate the concept of Callable Objects by implementing the __call__ method, which allows instances of a class to be invoked like functions:

1. Basic Callable Object

Creating an object that can be called like a function using __call__.

Copy

class CallableClass:
    def __call__(self, *args, **kwargs):
        return "Hello from __call__!"

obj = CallableClass()
print(obj())  # Output: Hello from __call__!

2. Callable Object with Arguments

Accepting arguments in the __call__ method.

Copy

class Adder:
    def __call__(self, a, b):
        return a + b

add = Adder()
result = add(5, 3)
print(result)  # Output: 8

3. Callable Object with Dynamic Behavior

The object changes its behavior based on internal state.

Copy


4. Callable Object with Return Value

Return a dynamic value based on the input.

Copy


5. Callable Object for Sorting

Using __call__ to sort elements dynamically.

Copy


6. Callable Object with Internal State Update

Callable object updates its internal state based on function calls.

Copy


7. Callable Object with Keyword Arguments

Accepting keyword arguments in __call__.

Copy


8. Callable Object for Function Composition

Using __call__ to chain or compose functions.

Copy


9. Callable Object with Default Parameters

Use default parameters inside the __call__ method.

Copy


10. Callable Object with Logging

Implement a callable object that logs its calls.

Copy


These examples showcase how you can create objects that behave like functions using the __call__ method, which makes them versatile and useful in a variety of contexts, such as dynamic behavior, function composition, logging, and more.

Last updated