__getattr__ python

class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream

"""
__getattr__为内置方法,当使用点号获取实例属性时,如果属性不存在就自动调用__getattr__方法
__setattr__当设置类实例属性时自动调用,如j.name=5 就会调用__setattr__方法 self.[name]=5
"""
def __getattr__(self, attr):
if attr in ('stream', '__getstate__'):
raise AttributeError(attr)
return getattr(self.stream,attr)

def writeln(self, arg=None):
if arg:
self.write(arg)
self.write('\n') # text-mode streams translate to \r\n if needed

posted @ 2020-08-12 11:04  峡谷恶霸  阅读(322)  评论(0编辑  收藏  举报