将函数用作字典键是否被认为是错误的形式?例如:
def add(a, b):
return a + b
mydict = {add: "hello"}
最佳答案
是的,这是完全正确的。例如,您可以使用它来存储一个函数被调用次数的计数器:
def hi():
print('hi')
funcs = {hi: 0}
print(funcs)
# {<function hi at 0x10fb39950>: 0}
for func in funcs:
func()
# hi
funcs[func] += 1
print(funcs)
# {<function hi at 0x10fb39950>: 1}
关于python - 使用函数作为字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27915710/