KetZoomer
KetZoomer

Reputation: 2915

Store Instance of Class in String

How can I store an instance of a class in a string? I tried eval, but that didn't work and threw SyntaxError. I would like this to work for user-defined classes and built-in classes (int, str, float).

Code:

class TestClass:
    def __init__(self, number):
        self.number = number

i = TestClass(14)
str_i = str(i)
print(eval(str_i)) # SyntaxError
print(eval("jkiji")) # Not Defined
print(eval("14")) # Works!
print(eval("14.11")) # Works!

Upvotes: 2

Views: 750

Answers (2)

timgeb
timgeb

Reputation: 78780

The convention is to return a string with which you could instantiate the same object, if at all reasonable, in the __repr__ method.

class TestClass:
    def __init__(self, number):
        self.number = number
    def __repr__(self):
        return f'{self.__class__.__name__}({self.number})'

Demo:

>>> t = TestClass(14)
>>> t
TestClass(14)
>>> str(t)
'TestClass(14)'
>>> eval(str(t))
TestClass(14)

(Of course, you should not actually use eval to reinstantiate objects in this way.)

Upvotes: 3

Selcuk
Selcuk

Reputation: 59445

You can also use the pickle built-in module to convert an object to a byte string and back:

import pickle

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
t2 = pickle.loads(s1)

then

print(t2.number)

will print

14

Upvotes: 2

Related Questions