Python全栈开发——类的内置attr属性

class Foo:
    def __init__(self,y):
        self.y=y
    #常用
    def __getattr__(self, item):#用在属性不存在时,会触发
         print('getattr')

    def __setattr__(self, key, value):#设置某一属性时,会触发
        #self.key=value 无限递归  错误
         self.__dict__['key']=value  #应该这样用
         print('setattr')
    def __delattr__(self, item):#在删除某一属性时,会触发
         print('delattr')

p=Foo(3)       #setattr
p.dd          #getattr
del   p.dd    #delattr
p.y=10       #setattr
#__getattr__,__setattr__,__delattr__做用
#作用于底层属性 #相当于重写了类中的这些内置方法
class Foo:
    def __init__(self,y):
        self.y=y
    #常用
    def __getattr__(self, item):#用在属性不存在时,会触发
         print('%s 不存在' %item)

     #筛选字符串
    def __setattr__(self, key, value):#设置某一属性时,会触发
        #self.key=value 无限递归  错误
        print('在在执行setattr')
        if type(value)==str:
            self.__dict__[key]=value  #应该这样用
        else:
             print('必须是字符串')
    def __delattr__(self, item):  #在删除某一属性时,会触发
         print('不允许删除')
f=Foo(88)
f.ss                #ss 不存在
print(f.__dict__)   #  {}
f.y='39'
print(f.__dict__)   #{'y': '39'}
del f.y             # 不允许删除
#二次加工标准类型(包装) 
#基于标准的数据类型,来定制自己的数据类型,新增或改写
class List(list):
    def append(self, obj):
        if type(obj) is str:
            super().append(obj)
        else:
            print('必须是字符串')

l=List('hggfj')
l.append(23)
print(l)       #['h', 'g', 'g', 'f', 'j']
l.append('Sb')
print(l)      #['h', 'g', 'g', 'f', 'j', 'Sb']
#授权:授权是包装的一个特性,授权过程,即是所有更新的功能都是 由新类的某部分
来处理,但已存在的功能授权给对象的默认属性

#实现授权的方式就是覆盖__getattr__方法
import time
class Open:
    def __init__(self,filename,mode='r',encode='utf-8'):
         #self.file封装了对文件的所有方法
        self.file=open(filename,mode,encoding=encode)

    def __getattr__(self, item):
        print(item,type(item))
        #getattr在self.file中找read属性(巧用)
        return getattr(self.file,item)

    #给写操作加时间(重写write)
    def write(self,line):
      t1=time.strftime('%Y-%m-%d %X',time.localtime())
      self.file.write('%s %s' %(t1,line))

f1=Open('a.txt','w')
print(f1.read)
#read <class 'str'>
#<built-in method read of _io.TextIOWrapper object at 0x001EAF30>
print(f1.write)
#write <class 'str'>
#<built-in method write of _io.TextIOWrapper object at 0x001EAF30>
f1.write('lujiacheng')

 

posted @ 2018-10-02 00:33  lujiacheng-python  阅读(157)  评论(0编辑  收藏  举报