Python class setup for serialization without pickl

2019-08-04 06:18发布

问题:

Scenario

I am looking for an object oriented approach in python that makes it possible to save an instance of a class in a data file and also load it again in at a later point in time. My current approach looks like this:

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)

As you can see ComplexParam1 and ComplexParam2 are to be calculated parameters and are not used for a first creation of the object A since they are very complex to get, whereas EasyParam1 and EasyParam2 are "known" parameters. Think of it as if the EasyParameters are integers and the ComplexParameters are large matricies that are constructed based on EasyParameters

So I am using the setup above to Save and Load objects to and from file, where Create uses the constructor since ComplexParam1 and ComplexParam2 are stored in file and do not need to be calculated again.

Problem

Up until now, the approach shown above worked just fine for me. Problems however arise, when this scheme is also used with class inheritances. So I am looking for a nicer and cleaner solution to my problem.

In C++ I would overload the constructor and make two possible creations of the class available, but this is not supported in python.

Any help, link and suggestion is appreciated.

回答1:

I think this is a case for the @classmethod decorator. For example, if you change the Load method to the following:

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

Then you could override the constructor:

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__.



回答2:

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.