嵩天老师Python面向对象-6,Python类的运算

 

class NewList(list):
    def __add__(self,other):
        result = []
        for i in range(len(self)):
            try:
                result.append(self[i] + other[i])
            except:
                result.append(self[i])
        return result

ls = NewList([1,2,3,4,5,6])
lt = NewList([1,2,3,4])
print(ls)
print(lt)
print(ls+lt)
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
[2, 4, 6, 8, 5, 6]

class NewList(list):
    def __contains__(self,item):
        s = 0
        for c in self:
            s += c
        if super().__contains__(item) or item == s:
            return True
        else:
            return False
ls = NewList([6,1,2,3])
print(ls)
[6, 1, 2, 3]

发布了423 篇原创文章 · 获赞 134 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/f2157120/article/details/105644613