Search code examples
pythonstringrepr

Python how to use the __str__ code for the __repr__?


I've stated programming in Phyton just few days ago, so I'm sorry if the question is quite easy.

I've written this code:

>>> class Polynomial:
        def __init__(self, coeff):
            self.coeff=coeff
        def __repr_(self):
            return str(self)
        def __str__(self):
            s=''
            flag=0;
            for i in reversed(range(len(self.coeff))):
                if(i==0):
                    s+= '+ %g ' % (self.coeff[i])
                elif (flag==0):
                    flag=1
                    s+= '%g z**%d' % (self.coeff[i],i)
                else:
                    s+= '+ %g z**%d ' % (self.coeff[i],i)
            return s

but __repr__ is not working:

>>> p= Polynomial([1,2,3])
>>> p
<__main__.Polynomial instance at 0x7fd3580ad518>
>>> print p
3 z**2+ 2 z**1 + 1 

How can i use the code wrritten in def __str__(self): without re-writining it? I couldn't find the answer anywhere else. thanks.


Solution

  • You are missing an underscore.

    Fix this line:

    def __repr_(self):    # BROKEN
    def __repr__(self):   # FIXED