def bar(): x = 13 def helloworld(): return "hello world, val of x:%d" % x print(methods.callf(helloworld))
def bar(): x = 13 def helloworld(): return "Привет, Мир! x = %d" % x print(helloworld.__closure__[0].cell_contents) return foo.callf(helloworld)
def bar(): x = 13 print("running bar..") # print(bar.__globals__) def helloworld1(): print(helloworld1.__globals__) return "Hello World. x is %d" % x print(foo.callf(helloworld1)) # returns 'Hello World, x is 13' print(helloworld1.__globals__)
import foo def helloworld(): return "Hello World! welcome." foo.callf(helloworld)
import foo x = 37 def helloworld(): print "Hello World. x is %d" % x foo.callf(helloworld)
print("a", a) '''function as objects and closures''' x = 4321 def helloworld(): return "hello world, val of x:%d" % x '''n the above case, the helloworld function uses the value of x that is defined in the same environment as where helloworld function is defined. Although variable 'x' with same name is define in the module where this function is being called, # that is not used. When the statements that make up a functions are packaged together with the environment in which they execute, the resulting object is known as closure ''' print(methods.callf(helloworld)) print(helloworld.__globals__) # in this one can see the '''when nested functions are used, closure capture the entire environment needed for the inner function to execute''' def bar(): x = 13 def helloworld(): return "hello world, val of x:%d" % x print(methods.callf(helloworld)) bar() '''closure is highly effective way to preserve state across a series of function calls'''