Python how to use the

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.


You are missing an underscore.

Fix this line:

def __repr_(self):    # BROKEN
def __repr__(self):   # FIXED
链接地址: http://www.djcxy.com/p/28316.html

上一篇: str()vs repr()函数在python 2.7.5中

下一篇: Python如何使用