I need to be able to convert any string representation of an object back into its original state on another computer. I will use the class, A, as my example:
class A:
def __init__(self):
self.data = "test"
self.name = "Bob"
def __str__(self):
return str(self.data) + " " + str(self.name)
An object of class A must be able to be recreated on a separate computer. So if a separate computer received (“A”, “memberData memberName”), it could convert this into an object of class A. I need this to be possible with any user defined object. Preferably I would like the user to only have to create a toString() and toObject() method.
You are looking at ways of serialising objects; this is a very standard problem.
pickleis the standard solution, and you should look into it first. If you want to make a class pickleable, you need to define some custom methods on it, and ensure the module in which it is defined can be found on both the source and destination computers. Then you canpickle.dumps(obj)which will return a string, andpickle.loads(my_str)to rebuild the object.Other options include
marshal(low-level) andjson(standard for web data).