1

设想

我在 python 中寻找一种面向对象的方法,它可以将类的实例保存在数据文件中,并在稍后的时间点再次加载它。我目前的方法如下所示:

class A(object):
    def __init__(self, ComplexParam1, ComplexParam2):
        self.ComplexParam1 = ComplexParam1
        self.ComplexParam2 = ComplexParam2

    @staticmethod
    def Create(EasyParam1, EasyParam2):
        #do some complex calculation to get ComplexParam1 and ComplexParam2 from EasyParam1 and EasyParam2
        return A(ComplexParam1, ComplexParam2)        

    def Save(self, Filename):
        #write ComplexParam1 and ComplexParam2 to disc

    @staticmethod
    def Load(Filename):
        #read ComplexParam1 and ComplexParam2 and call constructor
        return A(ComplexParam1, ComplexParam2)

正如您所看到的ComplexParam1,并且ComplexParam2是要计算的参数,并且不用于对象的第一次创建,A因为它们获取起来非常复杂,而EasyParam1EasyParam2是“已知”参数。把它想象成EasyParameters是整数,而ComplexParameters是基于构造的大型矩阵EasyParameters

所以我使用上面的设置SaveLoad对象来和来自文件,其中Create使用构造函数ComplexParam1,并且ComplexParam2存储在文件中,不需要再次计算。

问题

到目前为止,上面显示的方法对我来说效果很好。然而,当这个方案也与类继承一起使用时,问题就出现了。所以我正在寻找一个更好、更清洁的解决方案来解决我的问题。

在 C++ 中,我会重载构造函数并使两个可能的类创建可用,但这在 python 中不受支持。

任何帮助,链接和建议表示赞赏。

4

2 回答 2

1

我认为这是@classmethod装饰师的情况。例如,如果您将Load方法更改为以下内容:

    @classmethod
    def Load(cls, Filename):
        # Do stuff
        return cls(ComplexA, ComplexB)

然后你可以覆盖构造函数:

class B(A):
    def __init__(self, complexA, complexB):
        # Whatever you want, including calling the parent constructor

And, finally, you could call B.Load(some_file) which would invoke B.__init__.

于 2013-02-01T09:16:46.267 回答
0

Overloading in not needed, just use a classmethod for alternative contructor methods. Look at this questions and it's answers.

class A (object):

    @classmethod
    def Load(cls, Filename):
        #read ComplexParam1 and ComplexParam2 and call constructor
        return cls(ComplexParam1, ComplexParam2)

By using the cls parameter for the class, it works nice with inheritance.

于 2013-02-01T09:17:05.697 回答