How do you call an instance of a class in Python?

How do you call an instance of a class in Python?

You call an instance of a class as in the following:

o = object() # create our instance
o() # call the instance

But this will typically give us an error.

Traceback (most recent call last):
  File <stdin>, line 1, in <module>
TypeError: object object is not callable

How can we call the instance as intended, and perhaps get something useful out of it?

We have to implement Python special method, __call__!

class Knight(object):
    def __call__(self, foo, bar, baz=None):
        print(foo)
        print(bar)
        print(bar)
        print(bar)
        print(baz)

Instantiate the class:

a_knight = Knight()

Now we can call the class instance:

a_knight(ni!, ichi, pitang-zoom-boing!)

which prints:

ni!
ichi
ichi
ichi
pitang-zoom-boing!

And we have now actually, and successfully, called an instance of the class!

The short answer is that the object class has no __call__ method (you can check that with dir(object)). When you create an instance of a class the __init__ method is called and when you call the instance, the __call__ method is called.

How do you call an instance of a class in Python?

Up Votes for Everyone!
Thanks for posting the question and thanks for answering.

I thought I would just share my implementation in case that helps others …

I have a class (called RTS) and it contains an SQL Query that I access using a get. The class works fine as an independent endpoint. Now I want to call that class from within the program.

Using the answer above I added the following:

class RTS(Resource):
def __call__(self):
    print(In RTS)

def get(self, user_id):
    try: ...

In order to call the class from elsewhere in the program I added:

getGR = RTS.get(self, user_unique_id)

Voila – I got the same info I could check on Postman returned within the program.

Leave a Reply

Your email address will not be published. Required fields are marked *