InterviewSolution
| 1. |
What are decorators in Python? |
|
Answer» Decorators in Python are essentially functions that add functionality to an EXISTING function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example: # decorator function to convert to lowercasedef lowercase_decorator(function): DEF wrapper(): func = function() string_lowercase = func.lower() return string_lowercase return wrapper# decorator function to split wordsdef splitter_decorator(function): def wrapper(): func = function() string_split = func.split() return string_split return wrapper@splitter_decorator # this is EXECUTED next@lowercase_decorator # this is executed firstdef hello(): return 'Hello World'hello() # output => [ 'hello' , 'world' ]The beauty of the decorators LIES in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further MODIFY those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope. # decorator function to capitalize namesdef names_decorator(function): def wrapper(arg1, arg2): arg1 = arg1.capitalize() arg2 = arg2.capitalize() string_hello = function(arg1, arg2) return string_hello return wrapper@names_decoratordef say_hello(name1, name2): return 'Hello ' + name1 + '! Hello ' + name2 + '!'say_hello('sara', 'ansh') # output => 'Hello Sara! Hello Ansh!' |
|