Day.8定义自己的数据类型

基于继承的方式定义自己的列表类型:

class lxy(list):
    def append(self, p_object):
        # print("-->",p_object)
        if not isinstance(p_object,int):
            raise TypeError("must be int")
        super().append(p_object)
    def insert(self, index:int, p_object:int):
        # if not isinstance(index,int):
        #     raise TypeError("must be int")
        # if not isinstance(p_object,int):
        #     raise TypeError("must be int")
        super().insert(index,p_object)
l=lxy([1,2,3])
print(l)
l.append(4)
print(l)
l.insert(0,21341)
print(l)

作业:

基于授权定制自己的列表类型,要求定制的自己的__init__方法

定制自己的append:只能向列表加入字符串类型的值

定制显示列表中间那个值的属性(提示:property)

其余方法都使用list默认的(提示:__getattr__加反射)

class List():
    def __init__(self,*args):
        self.__l=list([*args])#真正的列表
    def append(self,value):
        if not isinstance(value,str):
            raise TypeError("must be str")
        else:
            self.__l.append(value)
    def __getattr__(self, item):#属性不存在的情况下会触发
        return getattr(self.__l,item)#反射:列表.使用方法并运行
    @property#取中间值这个功能伪装成一个变量
    def centervalue(self):
        if self.__l:
            return self.__l[divmod(len(self.__l),2)[0]]#列表长度用divmod内置函数(获得一个元组)除以2取整
        else:
            raise IndexError("centervalue from empty list")
a=List(1,2,3)
print(a)#<__main__.List object at 0x000000EC7BFDADD8>
a.append("lxy")
print(a.__dict__)#{'_List__l': [1, 2, 3, 'lxy']}
print(a._List__l)#[1, 2, 3, 'lxy']
# a.append(123)#抛出异常
a.pop(2)
print(a._List__l)#[1, 2, 'lxy']
a.insert(1,4)
print(a._List__l)#[1, 4, 2, 'lxy']
print(a.centervalue)#2
# b=List()#定义一个空列表
# print(b.centervalue)#抛出异常

 在类最后添加如下代码,真正实现列表的打印:

def __str__(self):  # 不写这个,打印a就是一个内存地址
    return str(self.__l)
print(a)#[1, 2, 3]
原文地址:https://www.cnblogs.com/lxyoung/p/6757687.html