How to cast type to custom python class

Consider a class;

class temp:
    def __init__(self):
        pass

      

I create an object for it;

obj = temp()

      

Convert it to string;

strObj = str(obj)

      

Now how can I convert strObj to a temporary class object ??

org = temp(strObj)

      

+3


source to share


2 answers


As Anand pointed out in the comments, you are looking for object serialization and deserialization. One way to achieve this is through the pickle module (or cPickle):

>>> import pickle

>>> class Example():
...     def __init__(self, x):
...             self.x = x
...
>>> a = Example('foo')
>>> astr = pickle.dumps(a) # (i__main__\nExample\np0\n(dp1\nS'x'\np2\nS'foo'\np3\nsb.
>>> b = pickle.loads(astr)
>>> b
<__main__.Example instance at 0x101c89ea8>
>>> b.x
'foo'

      



Note, however, that one way of using the pickle module is dealing with implementation versions. As suggested in the Python docs, if you want the uncovered instance to automatically handle the versioning implementation, you may need to add the version instance attribute and add a custom __setstate__ implementation: https://docs.python.org/2/library/pickle.html# object. SetState . Otherwise, the version of the object at serialization time will be exactly what you get at deserialization time, regardless of code changes made to the object itself.

0


source


For those looking for overrides such as int(obj)

, float(obj)

and str(obj)

, see Overloading int () in Python . You need to implement __int__

, __float__

or __str__

for an object.



+1


source







All Articles