定制自己的数据类型

两种方式:

继承的方式和授权的方式

继承的方式:
即:重新写父类的方法


#定义自己的数据类型,实例对象只能插入字符串类型,且只能添加整型
class List(list):

    def append(self, object):
        if not isinstance(object,int):
            return print("only append int type")

        super().append(object)

    def insert(self, index: int, object):
        if not isinstance(object,str):
            return print("only insert str type")
        super().insert(index,object)

实例化

l1 = List([1,2,3])
print(l1)
l1.append("a")
print(l1)
l1.append(3)
print(l1)


l1.insert(0,4)
print(l1)
l1.insert(0,"str")
print(l1)

执行结果

[1, 2, 3]
only append int type
[1, 2, 3] #未添加成功“a”
[1, 2, 3, 3]
only insert str type#未插入成功数字4
[1, 2, 3, 3]
['str', 1, 2, 3, 3]

授权方式:

open函数无法继承,只能通过getter方法实现

import time
class Open:
    def __init__(self,filepath,mode="r",encoding="utf-8"):
        self.x = open(filepath,mode=mode,encoding=encoding)
        self.filepath = filepath
        self.mode = mode
        self.encoding=encoding


    def write(self,line):
        t = time.strftime("%Y-&m-%d %X")
        print("%s:%s"%(t,line))
        self.x.write(line)

    def __getattr__(self, item):
        return getattr(self.x,item)

原文地址:https://www.cnblogs.com/greatkyle/p/6758554.html