如何在Python中调用类的实例? [英] How do you call an instance of a class in Python?
问题描述
这受到我刚刚看到的一个问题的启发,该问题是通过调用类实例来更改返回的内容,但是很快就得到了 __ repr __
的回答(并且被接受,所以提问者
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()
但我们会收到错误消息,例如 TypeError:'object'对象不可调用
。
but we'll get an error, something like TypeError: 'object' object is not callable
.
此行为在CPython 此处的源中定义。
This behavior is defined in the CPython source here.
因此,请确保我们在Stackoverflow上遇到以下问题:
So to ensure we have this question on Stackoverflow:
您如何真的在Python中调用了一个类的实例?
How do you actually call an instance of a class in Python?
推荐答案
您调用了一个类的实例如下所示:
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?
我们必须实现Python特殊方法 __ call __
!
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)
实例化课程:
a_knight = Knight()
现在我们可以调用类实例:
Now we can call the class instance:
a_knight('ni!', 'ichi', 'pitang-zoom-boing!')
其中会打印:
ni!
ichi
ichi
ichi
pitang-zoom-boing!
我们现在已经成功地将称为课!
And we have now actually, and successfully, called an instance of the class!
这篇关于如何在Python中调用类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!