I am learning the ropes in Python. When I try to print an object of class Foobar
using the print()
function, I ge
Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:
"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"
Given this class definition:
class Test(object):
def __init__(self, a, b):
self._a = a
self._b = b
def __str__(self):
return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)
def __repr__(self):
return 'Test("%s","%s")' % (self._a, self._b)
Now, is easy to serialize instance of Test
class:
x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print
y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print
So, running last piece of code, we'll get:
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
But, as I said in my last comment: more info is just here!