0

After having stored a serialized class object in a file, I would like to provide a static method "Load" which should reopen the file, deserialize the object and return a new instance.

Classically, I would approach this problem by overloading the constructor and pass in all necessary arguments. However, this is not the common in Python but one rather would adapt the following approach:

Python class setup for serialization without pickle

As I deserialize the object in a static method, there is no "cls" and by now I have no clue how to manage it. In short I want to have such a behavior:

x = Foo() # default constructor. All serializable data is created later on
# working with x and creating data
x.save("my_file.pkr")
y = Foo.Load(x)

The load() function looks like this:

    @staticmethod
    def load(filename):
        with open(filename, 'rb') as bin_object:
            lst1 = pickle.load(bin_object)
            lst2 = pickle.load(bin_object)
            lst3 = pickle.load(bin_object)
            lst4 = pickle.load(bin_object)
            lst5 = pickle.load(bin_object)

        # not possible as I already use the default constructor
        return Foo(lst1, lst2, lst3, lst4, lst5)

Can somebody disclose me how to create an object of Foo in the static load method? I still want to create "empty" objects by calling just Foo().

Community
  • 1
  • 1
null
  • 1,369
  • 2
  • 18
  • 38

1 Answers1

1

You're being misled by a Java way of doing things.

In Python, there is both staticmethod, which takes no arguments, and classmethod, which takes the class. The latter is what you want.

And there's no reason that attribute assignment has to be done in the constructor, or at initialize time at all. It's perfectly valid and idiomatic to assign attributes after initialization, and from outside the instance.

@classmethod
def load(cls, filename):
    with open(filename, 'rb') as bin_object:
        ...
    foo = cls()
    foo.lst1 = lst1
    foo.lst2 = lst2
    ...
    return foo
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Apparently "load()" takes one argument. This is a reference to a class object. But what reference is taken when calling it "Foo.Load()"? – null Jun 16 '15 at 18:07
  • The reference is to `Foo`. In Python classes, like functions, are first-class objects. – Daniel Roseman Jun 16 '15 at 21:14