Python:类的继承—创建一个子类,继承自内置数据类型list

1.问题

在这里插入图片描述

2.代码

class mylist(list):  # 继承父类list

    def product(self):  #新建方法
        m = 1
        for n in self:
            m = m * n
        return m

    def __add__(self, other):  #特殊方法
        if len(self) != len(other):  #判断输入数据是否等长
            raise ValueError
        mylst = mylist()

        for a, b in zip(self, other):
            c = a + b
            mylst.append(c)  #子类mylist继承父类的方法.append()
        return mylst

    def __mul__(self, other):
        if len(self) != len(other):
            raise ValueError

        mylst = mylist()
        for a, b in zip(self, other):
            c = a * b
            mylst.append(c)

        s_mul = sum(mylst)
        return s_mul

lst1 = mylist([1, 2, 3])  # 调用类: 类名(参数)
lst2 = mylist([2, 3, 4])
lst_pro = lst2.product()  # 方法的引用:对象.方法()
lst_pro1 = mylist.product(lst2)  #等价
print(lst_pro)
print(lst_pro1)

lst_add = lst1 + lst2  # 调用方法
lst_add1 = lst1.__add__(lst2)
print(lst_add)
print(lst_add1)

lst_mul = lst1 * lst2
lst_mul1 = lst1.__mul__(lst2)
print(lst_mul)
print(lst_mul1)

猜你喜欢

转载自blog.csdn.net/qq_40797015/article/details/113925407
今日推荐