你如何在 Python 中调用类的实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24253761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you call an instance of a class in Python?
提问by Aaron Hall
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).
这是受到我刚刚看到的一个问题的启发,“通过调用类实例更改返回的内容”,但很快得到了回答__repr__
(并被接受,因此提问者实际上并不打算调用该实例)。
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
.
但是我们会得到一个错误,比如TypeError: 'object' object is not callable
.
This behavior is defined in the CPython source here.
So to ensure we have this question on Stackoverflow:
所以为了确保我们在 Stackoverflow 上有这个问题:
How do you actually call an instance of a class in Python?
你实际上如何在 Python 中调用类的实例?
采纳答案by Aaron Hall
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__
!
我们必须实现 Python 的特殊方法,__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, calledan instance of the class!
我们现在实际上并成功地调用了类的一个实例!