Reputation: 18725
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?
Upvotes: 1
Views: 1842
Reputation: 1765
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
Upvotes: 2