Today I Learned

hashrocket A Hashrocket project

Call an object like a function with `__call__`

Using __call__ you can make an object behave like a function.

class HiyaPerson:
     def __init__(self, person_name):
         self.person_name = person_name
     def __call__(self):
         print("Hiya there, " + self.person_name)

hiya = HiyaPerson("Bob")
hiya()
# Hiya there, Bob

A side effect is that now a "function" can have state. Interesting!

class Counter:
    def __init__(self):
        self.count = 0
    def __call__(self):
        self.count += 1
   
count = Counter()
count()

import inspect 
dict(inspect.getmembers(count))['count']
# 1
count()
dict(inspect.getmembers(count))['count']
# 2
See More #python TILs