python - python字典中的函数

标签 python function dictionary syntax

我可以通过说将函数存储在字典中

MyDict = {}

def func():
    print("Hello, world!")

MyDict["func"] = func

我想知道是否有更干净/更简洁的方式来编写这个 - 类似于

MyDict = {}

def MyDict["func"]():
    print("Hello, world!")

但是这段代码会抛出一个语法错误

最佳答案

您可以(ab)使用装饰器。

MyDict = {}

def store(d, name):
    def _(f):
        d[name] = f
        return f
    return _

@store(MyDict, "func")
def func():
    print("Hello, world!")

@store(MyDict, "foo")
def some_other_func():
    print("Goodbye")

如果您只想使用定义的名称作为键并硬编码要更新的字典,则可以简化此操作:

def store(f):
    MyDict[f.__name__] = f
    return f

@store
def func():
    print("Hello, world!")

关于python - python字典中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051894/

相关文章:

python - Django 的 FormWizard 中的空 ModelFormset

javascript - 函数 - 将元素 id 作为参数传递

Python 创建列表字典

python - 没有名为组合的模块(来自 import wx.combo) - pyspread

python - 如何使用 SQLAlchemy 复制 Oracle 中的唯一约束?

javascript - 我无法理解 "Functions in Simplified JavaScript are lambdas with lexical scoping."

javascript - 未定义的内嵌函数

iphone - iPad内置词典

Python 字典数组 - 每个值一行

python - Python如何计算数字?