2017-03-15 71 views
-2

我前幾天在Phyton講過編程,所以如果問題很簡單,我很抱歉。Python如何爲__repr__使用__str__代碼?

我寫這段代碼:

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

如何,我可以使用,無需重新writining它def __str__(self): wrritten的代碼?我在其他地方找不到答案。 謝謝。

+1

通過重命名'__repr_'到'__repr__' –

回答

-2

您缺少下劃線。

修復此行:

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

請評論和投票關閉作爲一個拼寫錯誤,而不是回答的。 – Li357