[英]What happens when a function returns its own name in python?
def traceit(frame, event, trace_arg):
global stepping
if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command()
resume = debug(command, frame.f_locals)
return traceit
代碼中最后一行的含義是什么?
編輯:
def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif c == '"' or c == "'" and tag:
quote = not quote
elif not tag:
out = out + c
return out
def main():
print (remove_html_markup('xyz'))
print (remove_html_markup('"<b>foo</b>"'))
print (remove_html_markup("'<b>foo</b>'"))
# globals
breakpoints = {9: True}
stepping = False
def debug(command, my_locals):
global stepping
global breakpoints
if command.find(' ') > 0:
arg = command.split(' ')[1]
else:
arg = None
if command.startswith('s'): # step
stepping = True
return True
elif command.startswith('c'): # continue
stepping = False
return True
elif command.startswith('q'): # quit
sys.exit(0)
else:
print ("No such command", repr(command))
return False
commands = ['s', 's', 's', 'q']
def input_command():
#command = raw_input("(my-spyder) ")
global commands
command = commands.pop(0)
return command
def traceit(frame, event, trace_arg):
global stepping
if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command()
resume = debug(command, frame.f_locals)
return traceit
# Using the tracer
sys.settrace(traceit)
main()
sys.settrace(None)
函數是一個像其他任何人一樣的對象,所以返回自己沒有問題。 例如,它允許在同一行重復調用:
traceit("abc", "def", None)("ghi", "jkl", 3)("mno", "pqr", 4.3)
編輯: sys.settrace
設置全局跟蹤函數,每次輸入本地作用域以調用本地跟蹤函數時都會調用該函數。 這里它返回自己,以處理同一函數中的所有跟蹤。
有關詳細信息,請參閱https://docs.python.org/2/library/sys.html#sys.settrace 。
由於Python中的所有函數都是作為對象創建的,因此它返回對函數的引用。
它可以在代碼中稍后傳遞給另一個函數,或者使用任何函數調用參數調用。
def a(str):
print str
b = a # Assign an instance of a to b
b('hello') # Call b as if it were a
print type(b)
打印:
hello
<type 'function'>
https://docs.python.org/2/library/sys.html#sys.settrace
settrace允許您傳遞函數以用作調試器。 每次輸入新范圍時,都會調用您傳遞的函數。 它需要返回一個應該用於在該范圍內進行調試的函數。
由於該代碼的編寫者希望始終使用相同的函數,因此該函數返回自身。
來自鏈接的相關位:
每當輸入新的本地范圍時,都會調用跟蹤函數(事件設置為'call'); 它應返回對要使用該范圍的本地跟蹤函數的引用,如果不應跟蹤范圍 ,則返回None。
本地跟蹤函數應該返回對自身的引用(或者返回另一個函數以便在該范圍內進一步跟蹤) ,或者返回None來關閉該范圍內的跟蹤。
它返回一個函數對象。 我很好奇你是否在實時代碼中找到了這個以及用例可能是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.