• Python概念-定制自己的数据类型(包装)


    包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们刚学的继承/派生知识(其他的标准类型均可以通过下面的方式进行二次加工)

    实现方法被egon分成了两种:

    1."基于继承"实现的包装

    需求:定义一个只能包含数字的列表

    代码示例:

     1 # 编辑者:闫龙
     2 class Egon(list):
     3     def append(self, obj):#重写append方法
     4         if(type(obj) == int):#判断obj是否为一个int型
     5             super().append(obj)#调用父类的append方法将obj存放在列表中
     6         else:
     7             raise TypeError("Egon 只会数数")#主动抛出类型错误异常
     8     def insert(self, index:int,object:int):#重写insert方法
     9         if(isinstance(object,int)):#判断object是否为一个int型
    10             super().insert(index,object)#调用父类的insert方法将object存放在列表的index位置
    11         else:
    12             raise TypeError("都跟你说了,Egon只会数数")#主动抛出类型错误异常
    13 e=Egon([1,2,3])#实例化一个列表
    14 e.append(1)
    15 #e.append("1") 会抛出异常
    16 e.insert(0,1)
    17 #e.insert(0,"1") 会抛出异常
    18 print(e)
    实现全数字列表类型

    2."基于授权"实现的包装

    需求:不使用继承的方式,完成一个自己包装的文件操作

    代码示例:

     1 # 编辑者:闫龙
     2 class Open:
     3     def __init__(self,filename,mode,encoding): #在实例化Open的时候传入文件名称,打开方式,编码格式
     4         self.filename = filename
     5         self.mode = mode
     6         self.encoding = encoding
     7         #使用系统函数open()传入相应打开文件所需的参数,将文件句柄传递给self.file
     8         self.file = open(filename,mode=mode,encoding=encoding)#这里我总感觉是在作弊
     9     def read(self):#自己定义read方法
    10         return self.file.read()#返回self.file文件句柄read()的值
    11     def write(self,Context):#自己定义write方法
    12         self.file.write(Context+"
    ")#使用self.file文件句柄write方法将内容写入文件
    13         print(Context,"已写入文件",self.filename)
    14     # 利用__getattr__(),Attr系列中的getattr,当对象没有找到Open中传递过来的名字时,调用此方法
    15     def __getattr__(self, item):
    16         return getattr(self.file,item)#返回self.file文件句柄中,被对象调用,切在Open类中没有的名字
    17 
    18 MyFile = Open("a.txt","w+","utf8")
    19 MyFile.write("Egon is SomeBody")
    20 MyFile.close()
    21 MyFile = Open("a.txt","r+","utf8")
    22 print(MyFile.read())
    23 MyFile.seek(0)
    24 print(MyFile.readline())
    写了一个假Open!

    说实话,Egon,你后来讲的又特么快了!

    下次课的时候,你一定要把这个假Open讲一讲!

  • 相关阅读:
    MSVCRTD.lib(crtexe.obj) : error LNK2019: 无法解析的外部符号 _main,该符号在函数 ___tmainCRTStart
    (转)Spring MVC
    ios>android>javaee
    css标准导航代码
    图片对齐问题
    display:inline、block、inline-block的区别
    css怎么引用某张图片?链接要怎么写
    论怎么写好一篇实验报告
    路由器及其配置方法
    (转)MyEclipse2014配置Tomcat开发JavaWeb程序JSP以及Servlet
  • 原文地址:https://www.cnblogs.com/DragonFire/p/6757958.html
Copyright © 2020-2023  润新知