what is means reconstruct object or recreate object in python?
<p>I am trying to understand difference between <code>__str__</code> and <code>__repr__</code> and following <a href="http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python/2626364#2626364">Difference between __str__ and __repr__ in Python</a> </p>

<p>In the answer it says <code>__repr__</code>'s goal is to be unambiguous, I am confused what that really means. Another answer says: <code>__repr__</code>: representation of python object usually <code>eval</code> will convert it back to that object, so I have read that <code>eval</code> function let execute the python code in it.</p>

<p>Can someone please explain these terms in simple language:</p>

<ul>
<li>What is object reconstruction? </li>
<li>What is <code>__repr__</code>? </li>
<li>What is the connection between <code>eval</code> and <code>__repr__</code>?</li>
</ul>

<p>Perhaps a simple example will help clarify:</p>

<pre><code>class Object:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return 'Object({0.a!r}, {0.b!r})'.format(self)
</code></pre>

<p>This object has two parameters defined in <code>__init__</code> and a sensible <code>__repr__</code> method.</p>

<pre><code>&gt;&gt;&gt; o = Object(1, 2)
&gt;&gt;&gt; repr(o)
'Object(1, 2)'
</code></pre>

<p>Note that the <code>__repr__</code> of our object now looks exactly like how we created it to begin with; it's legal Python code that supplies the same values. As the <a href="https://docs.python.org/3/reference/datamodel.html#object.__repr__" rel="nofollow">data model documentation</a> puts it:</p>

<blockquote>
  <p>If at all possible, [<code>__repr__</code>] should look like a valid Python
  expression that could be used to recreate an object with the same
  value (given an appropriate environment).</p>
</blockquote>

<p>That's where <a href="https://docs.python.org/3/library/functions.html#eval" rel="nofollow"><code>eval</code></a> comes in:</p>

<pre><code>&gt;&gt;&gt; x = eval(repr(o))
&gt;&gt;&gt; x.a
1
&gt;&gt;&gt; x.b
2
</code></pre>

<p>Because the representation is Python code, we can <code>eval</code>ulate it and get an object with the same values. This is <em>"reconstructing"</em> the original object <code>o</code>.</p>

<p>However, as pointed out in the comments, this is just an illustration and doesn't mean that you should rely on <code>repr(eval(x))</code> when trying to create a copy of <code>x</code>.</p>

python python-3.x