2012-03-08 68 views
2

我试图设计一个接口来测试用户是否在类中运行某些功能之前登录。而不是:Python - 装饰类方法来测试类属性

class UserDoesStuff(object): 
    def doIfLoggedIn(self): 
     if self.checkLogin(): 
      [...do the stuff...] 

我在想,如果我能有这样的事情:

def protected(self): 
    if not self.checkLogin(): 
     raise UserLoginError() 

@protected 
def doIfLoggedIn(self): 
    [...do the stuff...] 

当然不工作的这一点,但有没有办法做到这一点使用的装饰?

回答

5

装饰(最简单的,没有多余的参数)预计用作输入:

import functools 

def protected(fun): 
    @functools.wraps(fun) 
    def wrapper(self, *args, **kwargs): 
     if not self.checkLogin(): 
      raise UserLoginError() 
     return fun(self, *args, **kwargs) 

    return wrapper # this is what replaces the original method 

@protected 
def doIfLoggedIn(self): 
    ... 
+0

这正是我所期待的!非常感谢。只要它让我接受,就会接受。 – 2012-03-08 15:45:33