Question

I have a class that I would like to 'reset' at times. Instead of manually clearing out all the variable in the class and all the modules it uses, I thought it might be a good idea to reconstruct it by calling init on itself. My concern is that I'm not quite sure if this is a good pattern, or if GC is clearing out the old objects correctly.

An example is below:

from modules import SmallClass
from modules import AnotherClass

class BigClass(object):
    def __init__(self, server=None):
        """construct the big class"""
        self.server = server
        self.small_class = SmallClass(self.server)
        self.another_class = AnotherClass(small_class)

    def reset_class(self):
        """reset the big class"""
        self.__init__(self.server)

Would this cause problems down the line, or is there a better way of going about this?

Was it helpful?

Solution

I suggest doing it the other way around:

from modules import SmallClass
from modules import AnotherClass

class BigClass(object):
    def __init__(self, server=None):
        """construct the big class"""
        self.reset_class(server)

    def reset_class(self, server=None):
        """reset the big class"""
        self.server = server
        self.small_class = SmallClass(self.server)
        self.another_class = AnotherClass(small_class)

This pattern is quite common as it allows __init__ to reset the class and you can separately reset the class as well. I have also seen this pattern in other object-oriented languages such as Java.

OTHER TIPS

It's safe to do, there's nothing magic about __init__ other than it's called automatically.

However, the normal thing to do is refactor common code into your reset_class method (which i'd call reset btw, class is already in the classname). THen just call reset from the __init__ method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top