[英]Can someone explain to me the difference between a Function Object and a Closure
所謂“功能對象”,是指在某種意義上可以調用的類的對象,可以在語言中將其視為函數。 例如,在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
...使用FunctionFactory和function會被視為閉包嗎?
本身不是,因為它不涉及范圍。 盡管它確實模仿了封閉的功能。
def ClosureFactory(val):
value = val
def closure():
nonlocal value # 3.x only; use a mutable object in 2.x instead
value += 1
return value
return closure
3>> closure = ClosureFactory(5)
3>> closure()
6
3>> closure()
7
閉包是一段代碼,它關閉在其定義的環境中捕獲其變量的代碼。 在大多數現代語言中,函數都是閉包,但不一定如此,並且您可以想象閉包不是函數對象(例如,根本不是對象的Ruby塊)。
這是關閉的基本測試:
def bar():
x = 1
def foo():
print x
return foo
x = 2
bar()()
如果輸出1,則foo
為閉包。 如果打印2,則不會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.