“函数对象”是指某个类的对象,它在某种意义上是可调用的,并且可以在语言中被视为函数。例如,在 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
我的问题是 - 这种对 FunctionFactory 和 function 的使用会被视为闭包吗?
最佳答案
闭包是一个函数,它会记住定义它的环境并且可以访问周围范围内的变量。函数对象是可以像函数一样调用的对象,但实际上可能不是函数。函数对象不是闭包:
class FunctionObject(object):
def __call__(self):
return foo
def f():
foo = 3
FunctionObject()() # raises UnboundLocalError
FunctionObject 无权访问创建它的范围。但是,函数对象的 __call__
方法可能是一个闭包:
def f():
foo = 3
class FunctionObject(object):
def __call__(self):
return foo
return FunctionObject()
print f()() # prints 3, since __call__ has access to the scope where it was defined,
# though it doesn't have access to the scope where the FunctionObject
# was created
关于python - 有人可以向我解释函数对象和闭包之间的区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584403/