Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following program: def my_decorator(func_to_decorate): def my_wrapp

ID: 3836291 • Letter: C

Question

Consider the following program: def my_decorator(func_to_decorate): def my_wrapper(*args, **kwargs): print ("In wrapper, wrapping {}" .format(func_to_decorate._name_)) result - func_to_decorate(*args, **kwargs) print ("Still in wrapper, returning wrapped {}". format (func_to_decorate._name_)) return result return my_wrapper @my_decorator def add_list1 (int_list): result_sum-0 for num in int_list: result_sum - result_sum + num print("In add_list1, res is {}". format(result_sum)) return result_sum def add_list2(int_list): return sum(int_list) add_list2 - my_decorator(add_list2) @my_decorator def print_stuff(str_var): print("In print_stuff...") return "print_stuff, val is {}".format(str_var) int_list - list (range (5)) print(add_list1(int_list)) print(add_list2(int_list)) print(print_stuff("random junk")) (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.

Explanation / Answer

b)

def my_decorator(func_to_decorate):
def my_wrapper(*args, **kwargs):
print("In wrapper, wrapping {}".format(func_to_decorate.__name__))
result = func_to_decorate(*args, **kwargs)
print("Still in wrapper, returning wrapped {}".format(func_to_decorate.__name__))
return result
return my_wrapper

@my_decorator
def add_list1(int_list):
result_sum = 0
for num in int_list:
result_sum = result_sum + num
print("in add_list1, res is {}".format(result_sum))
return result_sum

def add_list2(int_list):
return sum(int_list)

add_list2 = my_decorator(add_list2)

@my_decorator
def print_stuff(str_var):
print("In printstuff...")
return "print_stuff , val is {}".format(str_var)

int_list = list(range(5))

print(add_list1(int_list))

''' Output of add_list1 is

In wrapper, wrapping add_list1
in add_list1, res is 10
Still in wrapper, returning wrapped add_list1
10 '''


print(add_list2(int_list))

''' Ouput of add_list2 is

In wrapper, wrapping add_list2
Still in wrapper, returning wrapped add_list2
10'''

print(print_stuff("random junk"))

''' Output of print_stuff method is

In wrapper, wrapping print_stuff
In printstuff...
Still in wrapper, returning wrapped print_stuff
print_stuff , val is random junk'''

c ) @ property is called as the decorators in python.Decorators allow you to make simple modifications to callable objects like functions, methods, or classes.

the @decorator is used as an alternative for the given my_decorator method thats why whenever we are calling the methods add_list1,2 and print_stuff first it is calling my_decorator and then the given method.