Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

class

call

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?

like image 707
Russia Must Remove Putin Avatar asked Jun 16 '14 23:06

Russia Must Remove Putin


People also ask

How do I call an instance in Python?

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 instance a class in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

How do you call classes in Python?

To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.


1 Answers

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!

like image 199
Russia Must Remove Putin Avatar answered Sep 25 '22 00:09

Russia Must Remove Putin