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

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -