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

def reset(self):
    self.__init__()

or creating a new instance?

def reset(self):
    Foo()

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):

class Foo:
    def __init__(self):
        self.reset()
    def reset(self):
        # set all members to their initial value

You use it that way:

Foo foo      # create an instance
...
foo.reset()  # reset it

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

Foo foo      # create an instance
...
foo = Foo()  # make foo be a brand new Foo

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:

def reset(self):
    Foo()

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