|
问题来源于Python学习手册第六部分练习题,第二题,
一般情况下列表+字符串的运算会报错,为什么在类中定义了__repr__后就可以了呢?
情况一:
class MyList:
def __init__(self, start):
#self.wrapped = start[:] # Copy start: no side effects
self.wrapped = [] # Make sure it's a list here
for x in start: self.wrapped.append(x)
def __add__(self, other):
return MyList(self.wrapped + other)
if __name__ == '__main__':
x = MyList('spam')
x+'eggs'
运行结果:
TypeError Traceback (most recent call last)
<ipython-input-29-baa596820e4e> in <module>
8 if __name__ == '__main__':
9 x = MyList('spam')
---> 10 x+'eggs'
<ipython-input-29-baa596820e4e> in __add__(self, other)
5 for x in start: self.wrapped.append(x)
6 def __add__(self, other):
----> 7 return MyList(self.wrapped + other)
8 if __name__ == '__main__':
9 x = MyList('spam')
TypeError: can only concatenate list (not "str") to list
情况2:
class MyList:
def __init__(self, start):
#self.wrapped = start[:] # Copy start: no side effects
self.wrapped = [] # Make sure it's a list here
for x in start: self.wrapped.append(x)
def __add__(self, other):
return self.wrapped+list(other)
def _repr__(self):
return self.wrapped
if __name__ == '__main__':
x = MyList('spam')
print(x + ['eggs'])
运行结果:
['s', 'p', 'a', 'm', 'eggs']
|
|