0

Very headache questions

I have seen the code as bellow (in the Python lesson of Sololearn): def decor(func): def wrap(): #Question1: Why we have to add a function of wrap() inside the function of decor() print("============") func() print("============") return wrap #Question2: Why we have to add a return here, what's this exact meaning, and why we can't just write: "return" ? def print_text(): print("Hello world!") a=decor(print_text) a() #Question3: Why we can't just put "print(a)" here ? And why we have to put "()" after "a" ? >>>>OUTPUT: ============ Hello world! ============ I have 3 questions: Question1: Why we have to add a function of wrap() inside the function of decor() Question2: Why we have to add a return at end of loop, what's this exact meaning, and why we can't just write: "return" ? Question3: Why we can't just put "print(a)" at end ? And why we have to put "()" after "a" ?

7th Apr 2019, 10:59 PM
Joe Lishuai Lin
Joe Lishuai Lin - avatar
1 Respuesta
+ 2
Not so very headache answers Answer 1: It's just an implementation and not really necessary. You can directly write contents of wrap function in the decor without writing nested function. def decor(func): print("========") func() print("========") Answer 2: It's just to return warp function whenever decor is called so that you can call whatever is returned by decor function. Answer 3: decor is returning a function which is being stored in a and so now a is a function. print(a) will print the memory address of a. And why we've to put () after a? 'cause that's the syntax to call a function in Python.
8th Apr 2019, 1:34 AM
Шащи Ранжан
Шащи Ранжан - avatar