从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? 我该如何解决这个问题?


#1楼

参考:https://stackoom.com/question/1NDPs/从Python中的另一个文件调用函数


#2楼

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位于同一目录中。


#3楼

First of all you do not need a .py . 首先,你不需要.py

If you have a file a.py and inside you have some functions: 如果你有一个文件a.py和里面你有一些功能:

def b():
  # Something
  return 1

def c():
  # Something
  return 2

And you want to import them in z.py you have to write 你想在z.py导入它们,你必须写

from a import b, c

#4楼

First save the file in .py format (for example, my_example.py ). 首先以.py格式保存文件(例如, my_example.py )。 And if that file have functions, 如果该文件有功能,

def xyz():

        --------

        --------

def abc():

        --------

        --------

In the calling function you just have to type the below lines. 在调用函数中,您只需键入以下行。

file_name: my_example2.py file_name:my_example2.py

============================ ============================

import my_example.py


a = my_example.xyz()

b = my_example.abc()

============================ ============================


#5楼

You should have the file at the same location as that of the Python files you are trying to import. 您应该将文件放在与要导入的Python文件相同的位置。 Also 'from file import function' is enough. “从文件导入功能”也足够了。


#6楼

You don't have to add file.py . 您不必添加file.py

Just keep the file in the same location with the file from where you want to import it. 只需将文件保存在与要导入文件的文件相同的位置即可。 Then just import your functions: 然后只需导入您的功能:

from file import a, b

你可能感兴趣的:(python,file,function,import)