从方法中重新创建/重新分配类的最合适方法是什么?

时间:2016-06-19 02:33:17

标签: python class

假设我有一个名为School的类,它有一个名为createSchool的方法,它将创建一个新的School实例并替换现有实例(从中调用createSchool)...

伪代码如下:

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__

我的问题是我最终用现有实例的字典替换新创建的字典,这是最好的方法吗?

谢谢,
Sarith

2 个答案:

答案 0 :(得分:1)

我认为你可以使用@classmethod decorator

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

    @classmethod
    def createSchool(cls,schoolFile):
        schoolDict = parse(schoolFile)
        newClass = School(**schoolDict)
        return newClass

答案 1 :(得分:1)

更好的方法是删除调用实例。相反,这应该表示为一种类方法

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)

现在我们可以使用as:

school = School.createSchool(...)