python 我在类中做了个闭包..出错了



 class yoyo(object):
    def __init__(self):
        self.is_logined = False

    def login(self):
        print "do login"
        self.is_logined = True

    def login_required(self,func):
        @functools.wraps
        def wrapper(self,*args,**kwargs):
            return func(self,*args,**kwargs)
        if self.is_logined:
            return wrapper
        self.login()
        return wrapper

    @login_required
    def test_login(self):
        print 'testing:login'

代码出错: login_required() takes exactly 2 arguments (1 given)
第一次在类中写闭包,请教哪里出错了

python wrapper 闭包

喵咪木ちゃん 10 years, 3 months ago

正确答案 :


 class yoyo(object):
    def __init__(self):
        self.is_logined = False

    def login(self):
        print "do login"
        self.is_logined = True

    def login_required(self,func):
        @functools.wraps(func)
        def wrapper(self,*args,**kwargs):
            return func(self,*args,**kwargs)
        if self.is_logined:
            return wrapper
        self.login()
        return wrapper

    @login_required
    def test_login(self):
        print 'testing:login'

setse answered 10 years, 3 months ago

你的login_required只得到了test_login一个参数,还需要有self。
login_required改成这样:


 def login_required(func):
        @functools.wraps
        def wrapper(self,*args,**kwargs):
            if not self.is_logined:
                self.login()
            return func(self,*args,**kwargs)

然后,login_required在python中通常称为装饰器。

kasumi2 answered 10 years, 3 months ago

Your Answer