I've read this SO question and the accepted answer.
Quote:
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
However, I am still not sure, where the parameter method
comes from, if I override an arbitrary method.
I'll try to explain what I've understood so far:
- The outer function gets its parameter from the notation of the decorator. The decorator gets one parameter, which is the interface, from which we get the method we want to override.
The result of the decorator is afunction
, which will replace the function, which we decorate with this decorator.- The assert statement checks if the method we want to override is really in the interface, which we gave as a parameter. This is what the actual use is, because now we cannot override not existing methods. If we still try to do this, we will have a failed assertion.
But I still don't get where the parameter method
comes from and why it is always the method and not the instance, of the class, in which we want to override a method. A class' method usually has self
as a parameter and that refers to the instance, or is that wrong?
I've also read this website. Seems like in their example, the decorator has to take the same parameters the decorated function takes.
So how comes we suddenly have the method and not the class as a parameter?
EDIT#1: On this website I found examples, where the outer function receives the function, which will be decorated, instead of the parameters for that function or the decorator. It seems the logic of how decorators work is dependent on the condition if there are arguments to the decoration or not. But what are those rules?
Example from that website:
def pass_thru(func_to_decorate):
def new_func(*original_args, **original_kwargs):
print "Function has been decorated. Congratulations."
# Do whatever else you want here
return func_to_decorate(*original_args, **original_kwargs)
return new_func
# Notice nothing here now
def print_args(*args):
for arg in args:
print arg
# Notice the change here
pass_thru(print_args)(1, 2, 3)