Python如何使用__str__代码为__repr__?
Python how to use the __str__ code for the __repr__?
几天前我已经在 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):
中编写的代码?我在别处找不到答案。
谢谢。
你少了一个下划线。
修复此行:
def __repr_(self): # BROKEN
def __repr__(self): # FIXED
几天前我已经在 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):
中编写的代码?我在别处找不到答案。
谢谢。
你少了一个下划线。
修复此行:
def __repr_(self): # BROKEN
def __repr__(self): # FIXED