简体   繁体   中英

Error: Decorator takes exactly 2 arguments (1 given)

I'm trying to make a little decorator which refreshes gui after change in the database. The problem is that I'm still getting error. It works when the function and decorator aren't parts of some class.

class Tasks_Handling_Class:

    def database_changed(self,func):
        func()
        self.refresh_tasks_attribute()

    @database_changed
    def add_task(self,name,desc,time_minutes):
        try:
            self.msq.insert_into_table('tasks',name,desc,time_minutes)
            self.refresh_tasks_attribute()
            return True
        except Exception as e:
            print e
            return False

TypeError: database_changed() takes exactly 2 arguments (1 given)

The only thing I want to do is to run self.refresh_tasks_attribute() method after add_task() method.

Could you give some advices?

A decorator takes a function as an argument and returns a new function. Here's a very simple example:

def noisy(func):
    def new_func(*args, **kwargs):
        print "hiyyyoooo!"
        func(*args, **kwargs)
    return new_func

You can use it on a function that's already defined by calling it like a regular function:

myfunc_noisy = noisy(myfunc)

or you can use the @ syntax, but only on the definition of a function:

@noisy
def myfunc():
    print "hi"

In your case, if you just want to call refresh_tasks_attribute() after the decorated function is called, then you really should consider how often you'd be doing that, because it might be easier to just manually call it. If you still want to use a decorator, it would look something like this:

def database_changed(func):
    def new_func(*args, **kwargs):
        self = args[0]
        return_val = func(*args, **kwargs)
        self.refresh_tasks_attribute()
        return return_val
    return new_func

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM