gpt4 book ai didi

python - 当一个函数在 python 中返回它自己的名字时会发生什么?

转载 作者:IT老高 更新时间:2023-10-28 21:08:09 25 4
gpt4 key购买 nike

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 - 当一个函数在 python 中返回它自己的名字时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25204896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com