python - Can someone explain to me the difference between a Function Object and a Closure -


by "function object", mean object of class in sense callable , can treated in language function. example, in python:

class functionfactory:     def __init__ (self, function_state):         self.function_state = function_state     def __call__ (self):         self.function_state += 1         return self.function_state  >>>> function = functionfactory (5) >>>> function () 6 >>>> function () 7 

my question - use of functionfactory , function considered closure?

a closure function remembers environment in defined , has access variables surrounding scope. function object object can called function, may not function. function objects not closures:

class functionobject(object):     def __call__(self):         return foo  def f():     foo = 3     functionobject()() # raises unboundlocalerror 

a functionobject not have access scope in created. however, function object's __call__ method may closure:

def f():     foo = 3     class functionobject(object):         def __call__(self):             return foo     return functionobject() print f()() # prints 3, since __call__ has access scope defined,             # though doesn't have access scope functionobject             # created 

Comments

Popular posts from this blog

c# - SelectList with Dictionary, add values to the Dictionary after it's assigned to SelectList -

how can i manage url using .htaccess in php? -

ios - I get the error Property '...' not found on object of type '...' -