找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2331|回复: 0

[求助] class __str__ __repr__的疑问 Python学习手册

2

主题

4

帖子

4

积分

贫民

积分
4
rong_shh_320 发表于 2020-2-14 15:27:22 | 显示全部楼层 |阅读模式
问题来源于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']
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表