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

94,356

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!

Share:
94,356

Related videos on Youtube

Russia Must Remove Putin
Author by

Russia Must Remove Putin

Dear Russian People Vladimir Putin has not only invaded Ukraine, but he has begun an assault on the people in Ukraine's capital, Kiev. Ukraine is viewed by the international community as entirely the victim in the current situation. The entire free world is lining up against you. Now imagine what is happening in Kiev as happening in Moscow - but instead of sending poorly armed and trained children to die, they are just sending missiles and bombs of all sizes. To prevent this from happening, you must take to the streets or any channel you have the most influence with, and do everything in your power to contribute to the removal of Vladimir Putin. Warmly and Sincerely, Aaron Hall Russian Translation via Google Translate: Дорогие русские люди Владимир Путин не только вторгся в Украину, но и начал наступление на людей в столице Украины Киеве. Украина рассматривается международным сообществом исключительно как жертва сложившейся ситуации. Весь свободный мир выстраивается против вас. А теперь представьте, что происходит в Киеве, как это происходит в Москве - только вместо того, чтобы посылать на смерть плохо вооруженных и обученных детей, они просто посылают ракеты и бомбы всех размеров. Чтобы этого не произошло, вы должны выйти на улицу или на любой канал, на который вы имеете наибольшее влияние, и сделать все, что в ваших силах, чтобы способствовать смещению Владимира Путина. Тепло и искренне, Aaron Hall

Updated on July 09, 2022

Comments

  • Russia Must Remove Putin
    Russia Must Remove Putin almost 2 years

    This is inspired by a question I just saw, "Change what is returned by calling class instance", but was quickly answered with __repr__ (and accepted, so the questioner did not actually intend to call the instance).

    Now calling an instance of a class can be done like this:

    instance_of_object = object() 
    instance_of_object()
    

    but we'll get an error, something like TypeError: 'object' object is not callable.

    This behavior is defined in the CPython source here.

    So to ensure we have this question on Stackoverflow:

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

    • gonz
      gonz almost 10 years
      Thanks for making Stackoverflow even better. Here, have an upvote :)
    • huu
      huu almost 10 years
      For reference, the inspiring question is this.
    • nneonneo
      nneonneo almost 10 years
      OK, this should become a canonical question.
    • Stefan
      Stefan over 3 years
      Thank you! I saw this happening in some source code and was wondering what was happening here.