Why can this run? How do arguments work in Python when a function contains another? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why can this run? How do arguments work in Python when a function contains another?

def decor(func): def wrap(arg): print("***") func(arg) print("***") print("END OF PAGE") return wrap def invoice(num): print("INVOICE #" + num) invoice = decor(invoice) invoice(input()) In this code, the argument of wrap and invoice have different names, namely num and arg, though they are intended to be the same argument. But python recognizes it anyway. Is it because python uses function to identify argument, so it doesn't matter as long as they are both parameter of "func"? But if I change either one of the arg into num, it will throw me an error. How are arguments passed on altogether??

4th Aug 2021, 6:34 AM
薛阳
薛阳 - avatar
1 Answer
+ 4
Let me walk you through while it gets executed. invoice = decor(invoice) invoice(input()) You are passing the old invoice function to the decor function, decor function does something (decorates) and returns a new function which you get and store to invoice variable. Then you call the new invoice passing the user input. The decor function accepts a function as argument. It defines a new temporary function called wrap which returns it. When you later call the returned function the code inside wrap is executed, instead of the old invoice. You can think func(arg) as being invoice(arg)
4th Aug 2021, 7:14 AM
Giorgos