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?
You call an instance of a class as in the following:
But this will typically give us an error.
How can we call the instance as intended, and perhaps get something useful out of it?
We have to implement Python special method,
__call__
!Instantiate the class:
Now we can call the class instance:
which prints:
And we have now actually, and successfully, called an instance of the class!