我假設你知道JavaScript的arguments.callee
has been deprecated。無論如何,下面有幾種方法可以在Python中做類似的事情,以至於你可能還沒有看到。
使用情況管理器:
class wrapped(object):
def __init__(self, func):
self.func = func
def __enter__(self):
def wrapper(*args, **kwargs):
return self.func(self.func, *args, **kwargs)
return wrapper
def __exit__(self, *args):
pass
def test(callee, value=None):
if value is None:
print 'function attribute "x" is {}'.format(callee.x)
else:
print 'setting function attribute "x" to {}'.format(value)
callee.x = value
with wrapped(test) as test:
test(42) # -> setting function attribute "x" to 42
test() # -> function attribute "x" is 42
另一種更容易使用的方式是用一個函數裝飾:
from functools import wraps
def deco(f):
@wraps(f)
def wrapper(*args, **kwargs):
return f(f, *args, **kwargs)
return wrapper
@deco
def test(callee, value=None):
if value is None:
print 'function attribute "x" is {}'.format(callee.x)
else:
print 'setting function attribute "x" to {}'.format(value)
callee.x = value
test(42) # -> setting function attribute "x" to 42
test() # -> function attribute "x" is 42
有沒有這樣的參考,這就是爲什麼你提到的兩個職位在創建函數對象後,使用hack設置對函數本身的引用。 –
其他參考:[從框架獲取可調用對象](http://stackoverflow.com/q/1132543)和[Python:某些「\ _ \ _ magic \ _ \ _」屬性引用該函數內的函數] (http://stackoverflow.com/q/14986523) –
還有更多:[獲取代碼對象的Python函數](http://stackoverflow.com/q/12787108) –