Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/24253761/how-do-you-call-an-instance-of-a-class-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...