Code 21: Magic Method: __call__

Allowing instances to be called like functions
coding
python
Author

Tony Phung

Published

December 30, 2024

1. Create Tony_Counter Class

  • Instance attribute .counter defaulted to zero.

  • Instance method increment() increases .counter attribute by 1

  • Magic Method __call__() calls instance method increment():

  • In other words, when an instance calls itself with (), the instance.__call__() will be called:

    • In this case incrementing .counter by 1 each time.
class Tony_Counter():
    def __init__(self):
        self.counter: int = 0
        
    def increment(self):
        self.counter += 1
        
    def __call__(self):
        self.increment() 
ctr = Tony_Counter()
print(ctr.counter)
0
ctr.increment()
print(ctr.counter)
1
ctr.increment()
print(ctr.counter)
2