Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

python - 从Python中的另一个文件调用函数(Call a function from another file in Python)

Set_up: I have a .py file for each function I need to use in a program.

(Set_up:我有一个.py文件,用于我需要在程序中使用的每个函数。)

In this program, I need to call the function from the external files.

(在这个程序中,我需要从外部文件调用该函数。)

I've tried:

(我试过了:)

from file.py import function(a,b)

But I get the error:

(但我得到错误:)

ImportError: No module named 'file.py';

(ImportError:没有名为'file.py'的模块;)

file is not a package

(文件不是包)

How do I fix this problem?

(我该如何解决这个问题?)

  ask by user2977230 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There isn't any need to add file.py while importing.

(导入时无需添加file.py)

Just write from file import function , and then call the function using function(a, b) .

(只需from file import function写入,然后使用function(a, b)调用该函数。)

The reason why this may not work, is because file is one of Python's core modules, so I suggest you change the name of your file.

(这可能不起作用的原因是因为file是Python的核心模块之一,所以我建议你更改文件的名称。)

Note that if you're trying to import functions from a.py to a file called b.py , you will need to make sure that a.py and b.py are in the same directory.

(请注意,如果您尝试将函数从a.py导入到名为b.py的文件中,则需要确保a.pyb.py位于同一目录中。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...