Returning various objects when instantiating

When I instantiate a specific class that I wrote, I give it a name and several properties as arguments to __init__ . Given that the name has passed, my __init__ tries to find the file on disk that applies to that name, and instead of processing the rest of the arguments passed, it reads all the data from the file. And if the file is not found, arguments are used instead.

Now I wonder if I wanted to use pickle to store the entire object instead of using my own routines to write files, how would I upload? I can’t expand my object inside __init__ because the object is already created, right?

One of my ideas is to write a class method that I will use to create an instance instead, which returns an unpainted object if it is stored on disk, otherwise it will create a new object with the parameters passed.

Another idea is to use __new__ instead of a class method that will return an object, however I don't know if this is the intended use of __new__ .

Are these ideas good or is there a better way to achieve this?

+4
source share
2 answers

Use factory instead in __init__ . Example:

 class Foo(object): # whatever def get_foo(path, *args, **kwargs): try: obj = pickle.load(open(path)) if not isinstance(obj, Foo): raise TypeError, "%s does not contain a Foo" % path return obj except IOError as e: if e[0] == errno.ENOENT: return Foo(*args, **kwargs) else: raise 
+4
source

I really like using classmethod for this kind of thing, as it separates the special case logic from the standard class initialization logic. For instance.

 class MyClass(object): @classmethod def load(cls, name, **kargs): try: state = state_from_file(name) ## your loading code except Exception: state = kargs return cls(name, **state) def __init__(self, name, food=None, **kargs): self.name = name self.food = food d = MyClass(name='eric', food='spam & eggs') d = MyClass.load(name='eric', food='spam & eggs') 

How to save the state of an object ... I am not a fan of using pickles; No doubt this works, but it’s easier for me to explicitly save the state of your instance using the json, yaml format, etc. Feels "safer" in terms of platform compatibility, future validation, etc. It does not matter. If you adequately isolate your perseverance code, you can easily replace it.

0
source

All Articles