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

后端 未结 1 1418
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 11:55

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 q

相关标签:
1条回答
  • 2020-12-24 12:19

    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!

    0 讨论(0)
提交回复
热议问题