Search code examples
pythonfunctionclasscall

Python - 'call' a class


If I have a class, is there anyway to catch the event of calling it as if it were a function?

obj = ExampleClass()
obj() -- and error occurs because I am 'calling' a class instance

I would like to handle this event inside the actual class definition.


Solution

  • You can define a __call__ method on your class.

    class ExampleClass(object):
        def __call__(self):
            # do whatever you want here!