Python如何使用

我前几天在Phyton说过编程,所以如果问题很简单,我很抱歉。

我写了这段代码:

>>> 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

__repr__不起作用:

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

我如何在def __str__(self):使用代码wrritten def __str__(self):无需重写它? 我在其他地方找不到答案。 谢谢。


你缺少一个下划线。

修复这一行:

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

上一篇: Python how to use the

下一篇: Bring namedtuple's