题意:
假设已经存在函数 get_permissions可以获取当前用户的权限列表, 设计一个权限管理类,既可以作为装饰器,对一个函数授权,也可以作为上下文管理,对一段代码授权
例如


permissions = get_permissions()

if 'admin' in permissions:

    ## do somthings

else:

   rAIse Exception('Permissions denied')

分析:
权限检查的一般都是用装饰器的方法实现
demo:

def get_permissions():
    return "root" 

CLass Requrie:
    def __init__(self,permissions):
        self.permissions = permissions

    def check(self):
         if len(set(self.permissions).intersection(get_permissions())) <= 0:
                raise Exception('Permissions denied')

    def __call__(self,fn):
        @wraps(fn)
        def wrap(*args, **kwargs):
            self.check()
            return fn(*args, **kwargs)
        return wrap
    def __enter__(self):
        self.check()

    def __exit__(self, *args, **kwargs):
        pass

    def __get__(self, instance, cls): # 类作为装饰器,一定要这样用
        type.MethodType(self, instance)

@Requrie({"admin", 'root'})
def reboot():
    pass 

def kill():
    print("i will kill something")
    with  Requrie("root"):
        print('kill')