将函数用作字典键是否被视为不良形式?例如:
def add(a, b):
return a + b
mydict = {add: "hello"}
Run Code Online (Sandbox Code Playgroud)
是的,这完全有效.例如,您可以使用它来存储计数器调用函数的次数:
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}
Run Code Online (Sandbox Code Playgroud)
也就是说,这是一种倒退的做事方式.有一个更简单的类型作为字典键,如字符串或int更常见.