Python之组合的方式完成授权

初步模型
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 __getattr__(self, item):
        # print(item,type(item))
        #self.file.read
        return getattr(self.file,item) #把f1传给self,把read传给item,因此这里边getattr是,相当于通过文件句柄self.file调用他的相关方法
                            #get的f1.file下的read方法
f1 = Open("a.txt","w")
print(f1.__dict__)
print(f1.file)
print("==>",f1.read)  #因为类里没有read方法,所以触发__getattr__

sys_f = open("b.txt","w+")
print("-->",getattr(sys_f,"read"))

#结果
{'file': <_io.TextIOWrapper name='a.txt' mode='w' encoding='utf-8'>, 'mode': 'w', 'encoding': 'utf-8'}
<_io.TextIOWrapper name='a.txt' mode='w' encoding='utf-8'>
==> <built-in method read of _io.TextIOWrapper object at 0x00000000001AAC18>
--> <built-in method read of _io.TextIOWrapper object at 0x0000000001E92048>
```8
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容