• 【Python学习之旅】---继承的方式完成包装(授权、item系列、str&repr、format 自定义格式方法)


    #一、继承的方式完成包装

    class List(list): #继承list类
    def append(self,name):
    if type(name) is str: #判断如果添加的内容是字符窜,则添加到列表
    super().append(name) #则添加到列表

    def show_middle(self):
    middle=int(len(self)/2) #求中间的索引
    return self[middle] #返回对应的值


    l1=List('chenyuxia')
    print(l1)
    l1.append('sb') #添加内容
    print(l1) #打印列表
    print(l1.show_middle()) #打印中间的值

    #注意:用继承和派生


    #执行结果:

    ['c', 'h', 'e', 'n', 'y', 'u', 'x', 'i', 'a']
    ['c', 'h', 'e', 'n', 'y', 'u', 'x', 'i', 'a', 'sb']
    u

    #二、组合的方式完成授权

    #授权是包装的一种,覆盖__getaddr__来实现

    import time
    class FileHandle:
    def __init__(self,filename,mode='r',encoding='utf-8'):
    # self.filename=filename
    self.file=open(filename,mode,encoding=encoding) #打开一个文件,获取文件句柄
    self.mode=mode
    self.encoding=encoding
    def write(self,line):
    print('------------>',line)
    t=time.strftime('%Y-%m-%d %X') #获取当前时间
    self.file.write('%s %s' %(t,line)) #打印时间和日志信息

    def __getattr__(self, item):
    # print(item,type(item))
    # self.file.read
    return getattr(self.file,item)

    f1=FileHandle('a.txt','w+')
    #print(f1.file)
    #print(f1.__dict__)
    #print('==>',f1.read) #触发__getattr__,获取self.file的读的操作
    #print(f1.write) #触发__getattr__,获取self.file的写的操作
    f1.write('1111111111111111 ')
    f1.write('cpu负载过高 ')
    f1.write('内存剩余不足 ')
    f1.write('硬盘剩余不足 ')
    f1.seek(0)
    print('--->',f1.read())

    #执行结果:

    ------------> 1111111111111111

    ------------> cpu负载过高

    ------------> 内存剩余不足

    ------------> 硬盘剩余不足

    ---> 2020-01-06 21:02:01 1111111111111111
    2020-01-06 21:02:01 cpu负载过高
    2020-01-06 21:02:01 内存剩余不足
    2020-01-06 21:02:01 硬盘剩余不足

    三、item系列方法

    #通过操作字典的方式去调用访问
    class Name:
    def __getitem__(self, item):
    print('getitem',item)
    return self.__dict__[item]
    def __setitem__(self, key, value):
    print('setitem')
    self.__dict__[key]=value

    def __delitem__(self, key):
    print('delitem')
    self.__dict__.pop(key)

    n1=Name()
    n1['name']='chenyuxia'
    n1['age']=18
    print(n1.__dict__)
    del n1['age']
    print(n1.__dict__)

    print(n1['name'])

    #执行结果:

    setitem
    setitem
    {'name': 'chenyuxia', 'age': 18}
    delitem
    {'name': 'chenyuxia'}
    getitem name
    chenyuxia

    四、str和repr方法

    #两者都是控制打印实例本身的输出内容,只能return字符粗类型
    #自定制str方法
    class Foo:
    def __init__(self,name,age):
    self.name=name
    self.age=age

    def __str__(self): #控制打印实例F1的输出内容,prtint函数
    return '这是str'

    def __repr__(self): #应用在解释器
    return '名字是%s,年龄是%s ' % (self.name, self.age)



    F1=Foo('chenyuxia',18)

    print(F1) #str(F1)-->F1.__str()-->F1.__repr__() ,没有str,再找repr

    #执行结果:
    这是str


    五、自定义格式化方法format
    dic={
    'ymd':'{0.year} {0.mon} {0.day}',
    'd-m-y':'{0.year}-{0.mon}-{0.day}',
    'y:m:d':'{0.year}:{0.mon}:{0.day}'
    }

    class Foo:
    def __init__(self,year,mon,day):

    self.year=year
    self.mon=mon
    self.day=day
    def __format__(self, format_spec):
    if not format_spec or format_spec not in dic: #当用户不提供格式,或者是提供的格式不在字典中
    format_spec='ymd' #设置显示默认的格式
    fm=dic[format_spec] #获取用户输入的格式,获取对应内容
    return fm.format(self) #返回对应格式的时间内容

    f1=Foo(2016,1,4)
    print(format(f1,'55555')) #提供self和format_spec对应的参数


    #执行结果:
    2016 1 4
     
  • 相关阅读:
    Linux目录
    find命令
    107. Binary Tree Level Order Traversal II
    grep命令
    110. Balanced Binary Tree
    111. Minimum Depth of Binary Tree
    什么是泛型
    自动装箱与拆箱
    HDU 3001 Travelling (状压DP + BFS)
    POJ 3411 Paid Roads (状态压缩+BFS)
  • 原文地址:https://www.cnblogs.com/chenyuxia/p/12158540.html
Copyright © 2020-2023  润新知