Consider the following program: (a) Describe the purpose and use of a decorator
ID: 3830243 • Letter: C
Question
Consider the following program: (a) Describe the purpose and use of a decorator function. Your answer should include a description of what happens when a function is "decorated". (b) Describe what happens when the program is run. What results are produced? comment on the way add_list2 is called as opposed to the way add_list1 is called. (c) Describe the use of the @property syntax in the context of an instance variable of an object. (d) Describe the purpose and use of the * args and **kwargs parameters in the program. What is the content of_name_in func_to_decorate._name_? Why would you use this variable?Explanation / Answer
a)decorator functions are used to modify the functionality of a function with out creating a subclass.
Decorator function is a function which takes another function as argument and extends the behaviour of that function with out modifying it.
def my_decorator(fun):
def wrapper():
print("before the function")
fun()
print("after the function")
return wrapper
def fun2():
print("in function")
fun2=my_decorator(fun2)
fun2()
Here we have used my_decorator function to extend the functionality of fun2 with out modifying the actual function fun2
the output will bw
before the function
in function
after the function.
This explains the use of decorator function.
d)Decorator function can be used effectively with the help of arguments,* args and **kargs are used as parameters to the wrapper function.Wrapper function can now accept arbitrary number of arguments and keyword arguments.
_name_ is a special variable used in python,whrn the python interpreter reads the source file the value of _name_uses it to import any modules necessary for execution.If the current module is the main program then _name_ is set to _main_ other wise if the file is imported from other module then the name of that module is set to _name_.