嵩天老師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]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章