如何在Python中调用类的实例?

如何在Python中调用类的实例?,第1张

如何在Python中调用类的实例

您可以按以下方式调用类的实例:

o = object() # create our instanceo() # call the instance

但这通常会给我们带来错误。

Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'object' object is not callable

我们如何按预期方式调用该实例,并从中获得一些有用的信息?

我们必须实现Python特殊方法

__call__

class Knight(object):    def __call__(self, foo, bar, baz=None):        print(foo)        print(bar)        print(bar)        print(bar)        print(baz)

实例化该类:

a_knight = Knight()

现在我们可以调用类实例:

a_knight('ni!', 'ichi', 'pitang-zoom-boing!')

打印:

ni!ichiichiichipitang-zoom-boing!

现在,我们实际上已经成功地 调用 了该类的实例!



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5649293.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存