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

微笑、不失礼 提交于 2019-11-30 03:05:07

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!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!