12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Python</strong> provides some built-in function decorators for operations such as markingstatic methods, but programmers can also code arbitrary decorators of their own.Although they are not strictly tied to classes, user-defined function decorators oftenare coded as classes to save the original functions, along with other data, as stateinformation.Syntactically, a function decorator is a sort of runtime declaration about the functionthat follows. A function decorator is coded on a line just before the def statement thatdefines a function or method and consists of the @ symbol, followed by what we call ametafunction—a function (or other callable object) that manages another function.Static methods today, for example, may be coded with decorator syntax like this:class C:@staticmethoddef meth( ):...Internally, this syntax has the same effect as the following (passing the functionthrough the decorator and assigning the result back to the original name):class C:def meth( ):...meth = staticmethod(meth)# Rebind nameThe net effect is that calling the method function’s name actually triggers the resultof its staticmethod decorator first. Because a decorator can return any sort of object,this allows the decorator to insert a layer of logic to be run on every call. The decoratorfunction is free to return the original function itself or a new object that saves theoriginal function passed to the decorator to be invoked indirectly after the extra logiclayer runs.In fact, decorator syntax supports adding multiple layers of wrapper logic to a decoratedfunction or method. A decorator line of this form:@A @B @Cdef f( ):...runs the same as the following:def f( ):...f = A(B(C(f)))It passes the original function through three different decorators, and assigns theresult back to the original name. Again, the net effect is that when the original functionname is called, three layers of logic can be invoked to augment the originalfunction.Function Decorators | 557

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!