python - 使用函数作为字典键

标签 python

将函数用作字典键是否被认为是错误的形式?例如:

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/

相关文章:

python - 使用 if 条件比较使用 python 的密码

python - Pandas:标记另一列标志之间的值

python - Pygame 属性,init()

python - 当迭代高达 40,000 时,图像分析加速 "for-loop"

python - Pandas iloc 返回的范围与 loc 不同

python - Twisted - 我需要定期连接/断开客户端连接

python - 使用 django-taggit,是否可以将标签限制为预先批准的值?

python - 使用 Python 2.7 在包含 .py 的文件夹的子文件夹中调用应用程序

python - 在方法链接期间临时保留对对象的更改

python - Python构造函数中异常的单元测试