import time
class FileHandle:
def __init__(self,filename,mode,encoding='utf-8'):
self.file = open(filename,mode,encoding=encoding) #1 获取open类操作,赋值给类里面file变量 self.file = open('a.txt','r+',encoding='utf-8')
self.mode = mode
self.encoding = encoding

def write(self):
t = time.strftime('%Y-%m-%d %X')
self.file.write('%s 123123' %t) #4 self.file 剩余上面 self.file = open(filename,mode,encoding=encoding)打开文件操作 内存地址<_io.TextIOWrapper name='a.txt' mode='r+' encoding='utf-8'> 找到这个对象的write方法,写入数据

def __getattr__(self, item):
#self.file 等于 open(filename,mode,encoding=encoding)
return getattr(self.file,item) #self.file = <_io.TextIOWrapper name='a.txt' mode='r+' encoding='utf-8'> item = read 意思是<_io.TextIOWrapper name='a.txt' mode='r+' encoding='utf-8'>内存里面找这个read方法,找到了返回回去了


#写
F = FileHandle('a.txt','r+') #2 执行初始化
F.write() #3 找到write 方法,执行操作

#读
F.read #5 F.read先去实例里面找,read属性,找不到,就去类里面找,也找不到就执行了__getattr__方法
print(F.read) #6 找到的read 方法返回了一个read内存地址 <built-in method read of _io.TextIOWrapper object at 0x0073BDB0> = return getattr(self.file,item)
print(F.read()) #7 执行这个内存地址中的read方法,就读取到 a.txt 中的所有内容


posted on 2018-05-18 16:12  Python哥  阅读(247)  评论(0编辑  收藏  举报