Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (12.7k points)

Can anyone tell me, In python, how to call an instance of a class?

1 Answer

0 votes
by (26.4k points)

You can call the instance using below code:

o = object() # create our instance

o() # call the instance

But this will give error:

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'object' object is not callable

How might we call the instances as expected, and maybe receive something helpful in return? 

We need to execute Python's unique technique, __call__!

class Knight(object):

    def __call__(self, foo, bar, baz=None):

        print(foo)

        print(bar)

        print(bar)

        print(bar)

        print(baz)

Now, Instantiate the call:

a_knight=knight()

Now, try to call the instance of class

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

which will prints:

ni!

ichi

ichi

ichi

pitang-zoom-boing!

Are you interested to learn the concepts of Python? Join the python training course fast!

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)

Browse Categories

...