简体   繁体   English

Python如何包含另一个文件的功能

[英]Python how to include function from another file

I have a problem with including a function from another file to main executable script. 我在从另一个文件到主要的可执行脚本中包含一个函数时遇到问题。 I have too many functions and my main script became too long and hard to manage. 我的功能太多,我的主脚本变得太长且难以管理。 So i've decided to move every function to separate file and than attach/include it. 因此,我决定将每个功能移至单独的文件,然后将其附加/包括在内。 I've read nearly any relative post here to resolve my problem but no luck. 我读过几乎所有相关文章都可以解决我的问题,但是没有运气。 Let's see: 让我们来看看:

main_script.py
==================
from folder.another_file import f_fromanotherfile

class my_data:
     MDList=[]

work=my_data()

def afunction():
    f_fromanotherfile()
    return

and

another_file.py
=====================
#In this file i've put just function code
def f_fromanotherfile():
    a=[1,2,3,4]
    work.MDList=a
    return

And this is the error: 这是错误:

line 11, in f_fromanotherfile work.MDList=a NameError: global name 'work' is not defined f_fromanotherfile work中的第11行,MDList = a NameError:未定义全局名称'work'

Help me please 请帮帮我

The scope of 'work' is its module, main_script.py, so you cannot access it from another module. “工作”的范围是其模块main_script.py,因此您无法从其他模块访问它。 Make 'work' an argument of f_fromanotherfile instead: 将'work'设为f_fromanotherfile的参数:

In another_file.py: 在another_file.py中:

def f_fromanotherfile(work):
  # function body stays the same

In main_module.py: 在main_module.py中:

def afunction():
  f_fromanotherfile(work)

because in another_file.py 因为在another_file.py中

#In this file i've put just function code
def f_fromanotherfile():
    a=[1,2,3,4]
    work.MDList=a
    return 

work is not a global variable.And then doing assignment to it can't work. work不是全局变量,然后对其进行赋值将不起作用。

u should change ur code to: another_file.py 您应该将您的代码更改为:another_file.py

#In this file i've put just function code
def f_fromanotherfile():
    global work
    a=[1,2,3,4]
    work.MDList=a
    return

with the global keyword u can say the variable in so-called global scope and do ur assignment. 使用全局关键字,您可以在所谓的全局范围内说出变量并进行赋值。

PS:kind of like the keyword extern in C? PS:有点像C中的关键字extern吗?

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

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