Python Class Setup For Serialization Without Pickle
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 t
Solution 1:
I think this is a case for the @classmethod
decorator. For example, if you change the Load
method to the following:
@classmethoddefLoad(cls, Filename):
# Do stuffreturn cls(ComplexA, ComplexB)
Then you could override the constructor:
classB(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__
.
Solution 2:
Overloading in not needed, just use a classmethod
for alternative contructor methods. Look at this questions and it's answers.
classA(object):
@classmethod
def Load(cls, Filename):
#read ComplexParam1 and ComplexParam2 and call constructorreturn cls(ComplexParam1, ComplexParam2)
By using the cls parameter for the class, it works nice with inheritance.
Post a Comment for "Python Class Setup For Serialization Without Pickle"