Python:在同一实例上多次调用__init __() [英] Python: multiple calls to __init__() on the same instance

查看:344
本文介绍了Python:在同一实例上多次调用__init __()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__init__()函数在创建对象时被调用. 创建对象后,是否可以再次调用对象__init__()函数?

The __init__() function gets called when object is created. Is it ok to call an object __init__() function again, after its been created?

instance = cls(p1=1, p2=2)
# some code
instance.__init__(p1=123, p2=234)
# some more code
instance.__init__(p1=23, p2=24)

为什么有人要在已创建的对象上调用__init__()?

why would anyone wanna call __init__() on an object that is already created?

好问题.我想重新初始化实例的字段.

good question. i wanna re-initialize the instance's fields.

推荐答案

在对象上多次调用__init__很好,只要对__init__进行了编码即可获得想要的效果(无论如何是).发生这种情况的一种典型情况(因此,最好为__init__编写适当的代码!-)是当类的__new__方法返回该类的实例时:确实会导致__init__

It's fine to call __init__ more than once on an object, as long as __init__ is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code __init__ appropriately!-) is when your class's __new__ method returns an instance of the class: that does cause __init__ to be called on the returned instance (for what might be the second, or twentieth, time, if you keep "recycling" instances via your __new__!-).

这篇关于Python:在同一实例上多次调用__init __()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆