Sarith Subramaniam Sarith Subramaniam - 5 months ago 8
Python Question

What is the most suitable way to recreate/reassign a class from within a method?

Let's say that I have a class called School, which has a method called createSchool which will create a new instance of School and replace the existing instance (from which createSchool was called)...

The pseudo-code is below:

class School(object):
def __init__(self,a=None,b=None):
self.a = a
self.b = b

def createSchool(self,schoolFile):
#...code to parse schoolFile and extract a,b and create a dict
# called schoolDict
newClass = School(**schoolDict)
#This step replaces the old dict with the new one, thereby reassigning all
# attributes.
self.__dict__ = newClass.__dict__


My question is the thing that I did in the end with replacing the dictionary of the existing instance with that of the newly created one, the best way to go about it?

Thanks,

Sarith

Answer

A far better approach is to not obliterate the calling instance. Instead, this should expressed as a classmethod

class School(object):
    def __init__(self,a=None,b=None):
        self.a = a
        self.b = b

    @classmethod
    def createSchool(cls, schoolFile):
        # code to parse schoolFile and extract a,b and create a dict called schoolDict
        ... 
        return cls(**schoolDict)

Now we can use as:

school = School.createSchool(...)