Preferred way of resetting a class in Python -
based on this post on codereview.
i have class foo
in python (3), of course includes __init__()
method. class fires couple of prompts , thing. want able reset foo
can start procedure on again.
what preferred implementation?
calling __init__()
method again
def reset(self): self.__init__()
or creating new instance?
def reset(self): foo()
i not sure if creating new instance of foo
leaves behind might affect performance if reset
called many times. on other hand __init__()
might have side-effects if not attributes (re)defined in __init__()
.
is there preferred way this?
you hold instance work in class attribute. whenever want reset class, reassign new instance attribute. here how implement approach:
class foo: instance = none # single instance def __init__(self, ...): # initialize instance if foo.instance not exist, else fail if type(self).instance none: # initialization type(self).instance = self else: raise runtimeerror("only 1 instance of 'foo' can exist @ time") @classmethod def reset(cls): cls.instance = none # first clear foo.instance __init__ not fail cls.instance = foo(...) # initialization can called
then, can access instance referring foo.instance
.
i chose have reset
class method, decorated @classmethod
. decorator, instance can reset calling foo.reset()
, , cls
parameter passed automatically method.
i prefer approach (which more or less singleton pattern) on suggest, because in situation, appears logical have single instance of foo
, since want reset it. therefore, find rather intuitive "force" use of single instance.
on other hand, have instance outside of class, , use reset
instance method, defined:
def reset(self): self.__init__()
but might not work well. want set attributes outside of __init__
method. calling __init__
not reset attributes. therefore, instance not reset expected. if hold single instance , reassign brand new one, you're absolutely clean.
regarding call "creating new instance", that's more or less chose, question store it. think makes sense keep warm in class itself.
by way, there shouldn't performance issue (as in "memory leak") solution, since 1 foo
instance referenced @ time, , creating new 1 de-reference previous one.
wiki
Comments
Post a Comment