0
def make(label): 
    def echo(message):
       print(label + ':' + message) 
    return echo

F = make('Spam')
F('Ham!') 
Spam:Ham!

My doubt here is that when make function exited, it returned the address of echo function. And now when we call echo function it still knows the label value. Since there is no label variable after make function exited. How did the echo function knows label value?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Pawandeep Singh
  • 830
  • 1
  • 13
  • 25
  • 3
    It does not "return the address of `echo` function". It returns a function **object**. That object has properties ... such as its closure. – donkopotamus Jan 14 '18 at 12:01
  • The `label` variable is still alive after `make` returns, as long as there is a function around that still refers to it (such as `echo` (bound to `F`)). – melpomene Jan 14 '18 at 12:03
  • I think you need to google for `python closure`, `label` will be alive until the `echo` lifecycle die. – atline Jan 14 '18 at 12:13
  • 1
    this could be useful https://stackoverflow.com/questions/14413946/what-exactly-is-contained-within-a-obj-closure – Albin Paul Jan 14 '18 at 12:13
  • 1
    A goodl artical: https://www.programiz.com/python-programming/closure – atline Jan 14 '18 at 12:31

0 Answers0