简体   繁体   English

从另一个 python 文件访问函数字典

[英]Accessing dictionary of functions from another python file

This is a sample code the recreates an error I am getting in my project.这是一个示例代码,它重新创建了我在项目中遇到的错误。 Maybe I am missing something, but cannot seem to understand what I am doing wrong here.也许我错过了一些东西,但似乎无法理解我在这里做错了什么。

I have two files:我有两个文件:

my_functions.py which contains the following code my_functions.py 包含以下代码

func_dict = {'f1': func1, 'f2': func2}

def func1():
    print('func1')

def func2():
    print('func2')

and a main.py that tries to load function dictionary and run each function:和一个试图加载 function 字典并运行每个 function 的 main.py:

from my_functions import func_dict

func_dict['f1']()
func_dict['f2']()

When I run main.py, I get an error on from my_functions import func_dict which says:当我运行 main.py 时,我from my_functions import func_dict得到一个错误,上面写着:

Exception has occurred: NameError name 'func1' is not defined发生异常:未定义 NameError name 'func1'

How do I fix this?我该如何解决? If I am doing something wrong, then please do correct me.如果我做错了什么,请纠正我。 I am basically trying to load a dictionary that relates easier to remember keys to more complicated function names in the module.我基本上是在尝试加载一个字典,该字典将更容易记住的键与模块中更复杂的 function 名称相关联。

Please place the 2 functions over the dictionary definition as the following and try again.请将 2 个函数放在字典定义上,如下所示,然后重试。 That should fix the NameError -那应该修复 NameError -

def func1():
    print('func1')

def func2():
    print('func2')

func_dict = {'f1': func1, 'f2': func2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM