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!
Related videos on Youtube
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, 2022Comments
-
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 almost 10 yearsThanks for making Stackoverflow even better. Here, have an upvote :)
-
huu almost 10 yearsFor reference, the inspiring question is this.
-
nneonneo almost 10 yearsOK, this should become a canonical question.
-
Stefan over 3 yearsThank you! I saw this happening in some source code and was wondering what was happening here.
-