Skip to content
Advertisement

Preferred way of resetting a class in Python

Based on this post on CodeReview.

I have a class Foo in Python (3), which of course includes a __init__() method. This class fires a couple of prompts and does its thing. Say I want to be able to reset Foo so I can start the procedure all over again.

What would be the preferred implementation?

Calling the __init__() method again

JavaScript

or creating a new instance?

JavaScript

I am not sure if creating a new instance of Foo leaves behind anything that might affect performance if reset is called many times. On the other hand __init__() might have side-effects if not all attributes are (re)defined in __init__().

Is there a preferred way to do this?

Advertisement

Answer

Both are correct but the semantics are not implemented the same way.

To be able to reset an instance, I would write this (I prefere to call a custom method from __init__ than the opposite, because __init__ is a special method, but this is mainly a matter of taste):

JavaScript

You use it that way:

JavaScript

Creating a new instance from scratch is in fact simpler because the class has not to implement any special method:

JavaScript

the old instance will be garbage collected if it is not used anywhere else

Both way can be used for normal classes where all initialization is done in __init__, but the second way is required for special classes that are customized at creation time with __new__, for example immutable classes.


But beware, this code:

JavaScript

will not do what you want: it will just create a new instance, and immediately delete it because it will go out of scope at the end of the method. Even self = Foo() would only set the local reference which would the same go out of scope (and the new instance destroyed) at the end of the methos.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement