python 类的调用实例,如何在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?

解决方案

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 "", line 1, in

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值