演示嵌套函数定义及使用装饰器

def check_permission(func):
    '''演示嵌套函数定义及使用'''
    def wrapper(*args,**kwargs):
        if kwargs.get('username') != 'admin':
            raise Exception('Sorry,You are not allowed')
        return func(*args,**kwargs)
    return wrapper

class ReadWriteFile(object):
    # 把函数作为装饰器使用
    @check_permission
    def read(self,username,filename):
        return open(filename,'r').read()
    def write(self,username,filename,content):
        open(filename,'a+').write(content)
    # 作为普通函数使用
    write = check_permission(write)

t = ReadWriteFile()
print(t.read(username='admin',filename=r'c:\Users\PGIDYSQ\Desktop\1111111e.gen'))
print("*"*60)
t.write(username='admin',filename=r'c:\Users\PGIDYSQ\Desktop\1111111e.gen',content='cvname')
print("-"*60)

 相关资料:https://www.cnblogs.com/lyox/p/8671098.html

posted @ 2018-05-19 10:26  goodTOgreat  阅读(236)  评论(0编辑  收藏  举报