def assignOrder(order): @decorator def do_assignment(to_func): to_func.order = order return to_func return do_assignment class Foo(): @assignOrder(1) def bar(self): print "bar" @assignOrder(2) def foo(self): print "foo"
This funny @assignOrder(1) above def bar(self) launches this:
Foo.bar = assignOrder(1)(Foo.bar)
assignOrder(1) returns a function that takes another function, changes it (adds the order field and sets it to 1 ), and returns it. Then this function is called by the function that it decorates (thus, its order field is set); the result replaces the original function.
This is a more convenient, more readable, and more convenient way to say:
def bar(self): print "bar" Foo.bar.order = 1
badp
source share