Note that annotation order does make a difference, if swapped around the execution order will change: thing_printer(thing_name): We’ll expand on the previous example by defining a new decorator which ’logs’ that a function has been called and applying it to thing_printer def logging_decorator(target):Īnd on execution: thing_printer("Bronze Sphere") Which behave as expected: joe = person("Joe")ĭecorators can be nested to add multiple new behavious to a function or method. Object methods can also be decorated too using class person(): So the above: def thing_printer(thing_name):ĭecorated_thing_printer = start_end_time_decorator(thing_printer) Python’s offers a neater way to apply decorators and is especially handy when applying multiple decorators. We now have a decorated thing_printer which is really a reference to internal_wrapper itself containing a reference to thing_printer, we can execute the thing_printer as normal: decorated_thing_printer('Bronze Sphere') Pretty simple, it accepts a name and prints it out, now lets decorate it: decorated_thing_printer = start_end_time_decorator(thing_printer) To demonstrate, let’s define a new method and decorate it using the start_end_time_decorator so the start and end times are printed out. Upon execution the decorated function will perform the actions defined in our internal_wrapper plus any action of the original target function. When executed start_end_time_decorator will take in a target function and return a decorated reference (closure). To use a decorator we first define a decorator function, the example below outputs the start and end times of any function it’s applied to: from datetime import datetime What are Decorators?Ī decorator is a high-level construct that can be used to dynamically alter the functionality of a function, method or class. So in an attempt to counteract this forgetfulness let’s take a look at Python decorators and cover some of the basics. Python decorators always surprise me whenever I come across them as I’ll instantly forget everything about them within minutes of using one.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |