0

Could explain how this code gets executed line by line, I get confused with with it!!!

def smart_divide(func): def inner(a,b): print("I am going to divide",a,"and",b) if b == 0: print("Whoops! cannot divide") return return func(a,b) return inner @smart_divide def divide(a,b): return a/b

17th Jun 2020, 4:16 PM
Basemalzwawi Alzwawi
Basemalzwawi Alzwawi - avatar
1 Resposta
+ 2
First you define a function smart_divide. Inside it, you declare another function inner which is only accessible from inside smart_divide. Important thing to note is, the smart_divide function takes a function as parameter (func). The func variable can then be accessed by the inner function. Then, you declare some functionality for the function inner. That is, if parameter b == 0, you return None from the function. Else, you execute the func parameter taken in as an argument by the smart_divide function. Then you declare a function divide. The line "@smart_divide" Literally does this - divide = smart_divide(divide) So now when you call divide with arguements, you are actually calling the inner function, because smart_divide returns inner. I don't know how well I explained it. So this is a link to an excellent tutorial https://realpython.com/primer-on-JUMP_LINK__&&__python__&&__JUMP_LINK-decorators/
17th Jun 2020, 5:09 PM
XXX
XXX - avatar