【1.120】二次加工标准类型---包装

包装:python为大家提供了标准数据类型,以及丰富的内置方法,

其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,

新增/改写方法,

这就用到了我们刚学的继承/派生知识

(其他的标准类型均可以通过下面的方式进行二次加工)

1、二次加工标准类型(基于继承实现)

class List(list): #继承list所有的属性,也可以派生出自己新的,比如append和mid
    def append(self, p_object):
        ' 派生自己的append:加上类型检查'
        if not isinstance(p_object,int):
            raise TypeError('must be int')
        super().append(p_object)

    @property
    def mid(self):
        '新增自己的属性'
        index=len(self)//2
        return self[index]

l=List([1,2,3,4])
print(l)
l.append(5)
print(l)
# l.append('1111111') #报错,必须为int类型

print(l.mid)

#其余的方法都继承list的
l.insert(0,-123)
print(l)
l.clear()
print(l)

 2、clear 加权限

class List(list):
    def __init__(self,item,tag=False):
        super().__init__(item)
        self.tag=tag
    def append(self, p_object):
        if not isinstance(p_object,str):
            raise TypeError
        super().append(p_object)
    def clear(self):
        if not self.tag:
            raise PermissionError
        super().clear()

l=List([1,2,3],False)
print(l)
print(l.tag)

l.append('saf')
print(l)

# l.clear() #异常

l.tag=True
l.clear()
练习(clear加权限限制)

 

posted @ 2016-06-04 11:00  科学小怪癖  阅读(109)  评论(0)    收藏  举报