在 Python 中使用全局变量来“注册”函数是否可以接受?

问题描述 投票:0回答:0

众所周知,全局变量总是不好的。但是学习 python 装饰器,我发现这样的代码片段:

PLUGINS = dict()

def register(func):
    PLUGINS[func.__name__] = func
    return func

@register
def say_hello(name):
    return f"Hello {name}"

def get_function(func_name):
    return PLUGINS["func_name"]

我想用装饰器来注册一些函数,但是我很犹豫为什么要使用全局变量。看起来确实高效,但感觉不对。在这种情况下最好例外吗?或者有更好的方法吗?

python global-variables python-decorators
© www.soinside.com 2019 - 2024. All rights reserved.