Python基础第19天

                                                       面向对象基础讲解二

一:双下划线开头的attr方法

  • __getattr__()  只有属性不存在时,会触发
  • __setattr__()  设置属性时,会触发
  • __delattr__()  删除属性时会触发
class Foo:
    x=1
    def __init__(self,y):
        self.y=y                                    #__getattr__()

    def __getattr__(self, item):
        print('执行__getattr__')

f1=Foo(10)    #f1就是self
print(f1.y)
print(getattr(f1,'y'))
f1.sssssssssssssssss  #不存在时触发


class Foo:
    x=1
    def __init__(self,y):
        self.y=y                         #__delattr__()

    def __delattr__(self, item):
        print('执行__delattr__')

f1=Foo(10)
del f1.y
del f1.x



class Foo: x=1 def __init__(self,y): self.y=y def __setattr__(self,key,value): #__setattr__() print('执行__setattr__') # self.key=value #无限递归 self.__dict__[key]=value f1=Foo(10) print(f1.__dict__) f1.z=2 print(f1.__dict__)


class Foo: def __init__(self,name): self.name=name #只要是这种形式的就会触发__setattr__ def __getattr__(self, item): print('你找到属性【%s】不存在'%item) def __setattr__(self, k, v): print('执行__setattr__',k,v) if type(v)is str: print('开始设置') self.__dict__[k]=v else: print('必须是字符串类型') def __delattr__(self, item): print('执行delattr',item) self.__dict__.pop(item) f1=Foo('alex') print(f1.name) print(f1.age) print(f1.__dict__) f1.age=18 #会触发__setattr---- f1.gender='male' print(f1.__dict__) del f1.name print(f1.__dict__) #执行__setattr__ name alex #开始设置 #alex #你找到属性【age】不存在 #None #{'name': 'alex'} #执行__setattr__ age 18 #必须是字符串类型 #执行__setattr__ gender male #开始设置 #{'name': 'alex', 'gender': 'male'} #执行delattr name #{'gender': 'male'}

二:授权(包装的特性)

      所有更新的功能都是由新类的某部分来处理,但是已存在的功能就授权给对象的默认参数。

      实现授权的关键点就是覆盖__getattr__方法。

import time
class Open:
    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):
        t=time.strftime('%Y-%m-%d %X')
        self.file.write('%s %s'%(t,line))

    def __getattr__(self, item):
        # print(item,type(item))
        return getattr(self.file,item)  #通过字符串找到自己属性
#
#
#
f1=Open('a.txt','w')
print(f1.file)
print('--->',f1.read)

# sys_f=open('b.txt','w+')
# print(getattr(sys_f,'read'))

print(f1.write)
f1.write('1234\n')  
#2017-03-13 09:11:03 1234
# f1.seek(0) #  
f1.write(
'cpu负载过高\n')
f1.write(
'内存剩余不足\n')
f1.write(
'硬盘剩余不足\n')
#
2017-03-13 09:14:29 cpu负载过高
2017-03-13 09:14:29 内存剩余不足
2017-03-13 09:14:29 硬盘剩余不足


     例子核心点是:利用getattr通过字符串找到自己属性,通过返回给self.file拥有文件操作的功能。

 

posted @ 2017-03-13 09:19  清风徐来xyd  阅读(137)  评论(0编辑  收藏  举报