Python's preferred way to reset a class

Based on this post in CodeReview .

I have a class Fooin Python (3) which, of course, includes a method __init__(). This class runs a few tips and does its job. Say I want to be able to reset Fooin order to start the procedure again.

What would be the preferred implementation?

Method call __init__()again

def reset(self):
    self.__init__()

or create a new instance?

def reset(self):
    Foo()

I'm not sure that creating a new instance Fooreserves everything that can affect performance if resetcalled many times. On the other hand, it __init__()can have side effects if not all attributes (re) are defined in __init__().

Is there a preferred way to do this?

+4
2

, .

reset , ( __init__, , __init__ - , ):

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

:

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

, - :

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

,

, __init__, , __new__, .


, :

def reset(self):
    Foo()

, : , . self = Foo() , ( ).

+3

, , class. , reset , . :

class Foo:
    instance = None    # The single instance

    def __init__(self, ...):
        # Initialize the instance if Foo.instance does not exist, else fail
        if type(self).instance is None:
            # Initialization
            type(self).instance = self
        else:
            raise RuntimeError("Only one instance of 'Foo' can exist at a time")

    @classmethod
    def reset(cls):
        cls.instance = None        # First clear Foo.instance so that __init__ does not fail
        cls.instance = Foo(...)    # Now the initialization can be called

, Foo.instance.

reset , , @classmethod. reset, Foo.reset(), cls .

( ) , , Foo, reset . , "" .

, reset, :

def reset(self):
    self.__init__()

. , __init__. __init__ reset . reset, . , , , .

, " ", , , , . , .

, ( " " ) , Foo , .

+2

Source: https://habr.com/ru/post/1684125/


All Articles