找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1940|回复: 0

[求助] class 运算符重载 python学习手册

2

主题

4

帖子

4

积分

贫民

积分
4
rong_shh_320 发表于 2020-2-14 21:48:57 | 显示全部楼层 |阅读模式

题目Python学习手册第四版,第六部分练习题,第二题,让以类的形式重载列表运算
彩色地方是有疑问的:
1、红色部分:书上返回的是类的实例,直接返回列表不好吗?运行下来也可以,还是类比较喜欢这种嵌套的返回方式?
2、粉色部分:没有这两个运算定义,所有的测试也都能通过,是不是在3.0版本不需要__getslice__了,因为__getitem__就够了
     append也不需要了,因为有__getattr__就可以访问列表的append属性了?
书上的答案
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)
    def __mul__(self, time):
        return MyList(self.wrapped * time)
    def __getitem__(self, offset):
        return self.wrapped[offset]
    def __len__(self):
        return len(self.wrapped)
    def __getslice__(self, low, high):
        return MyList(self.wrapped[low:high])
    def append(self, node):
        self.wrapped.append(node)
    def __getattr__(self, name):       # Other methods: sort/reverse/etc
        return getattr(self.wrapped, name)
    def __repr__(self):
        return repr(self.wrapped)
if __name__ == '__main__':
    x = MyList('spam')
    print(x)
    print(x[2])
    print(x[1:])

    print(x + ['eggs'])
    print(x * 3)
    x.append('a')
    x.sort()
    for c in x: print(c, end=' ')
自己的code
class MyList:
    def __init__(self,start=[]):
        #self.data=start[:]#不能用此方法不能保证输出的是列表
        self.data=[]
        for index in start:
            self.data.append(index)
    def __add__(self,other):
        return self.data+other#为什么一定要用Mylist()返回的是类实例?
    def __getitem__(self,offset):
        return self.data[offset]
    def __getattr__(self, name):       # Other methods: sort/reverse/etc
        return getattr(self.data, name)
    def __mul__(self,times):
        return self.data*3
    def __len__(self):
        return len(self.data)
    def __repr__(self):
        return repr(self.data)

if __name__ == '__main__':
    x = MyList('spam')
    print(x)
    print(x[2])
    print(x[1:])

    print(x + ['eggs'])
    print(x * 3)
    x.append('a')
    x.sort()
    for c in x: print(c, end=' ')

回复

使用道具 举报

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

本版积分规则

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