File.py包含一个名为function的函数。如何导入?
from file.py import function(a,b)
上面给出了一个错误:
ImportError:没有名为'file.py'的模块;文件不是包
File.py包含一个名为function的函数。如何导入?
from file.py import function(a,b)
上面给出了一个错误:
ImportError:没有名为'file.py'的模块;文件不是包
当前回答
假设你想调用的文件是anotherfile.py,你想调用的方法是method1,那么首先导入文件,然后导入方法
from anotherfile import method1
如果method1是一个类的一部分,那么这个类是class1,那么
from anotherfile import class1
然后创建一个对象class1,假设对象名称为ob1,则
ob1 = class1()
ob1.method1()
其他回答
首先,从file.py导入函数:
from file import function
之后,使用以下方法调用函数:
function(a, b)
请注意,file是Python的核心模块之一,所以我建议您将file.py的文件名更改为其他内容。
请注意,如果您试图将函数从a.py导入到名为b.py的文件中,则需要确保a.py和b.py位于同一目录中。
首先将文件保存为.py格式(例如my_example.py)。 如果那个文件有函数,
def xyz():
--------
--------
def abc():
--------
--------
在调用函数中,您只需键入下面的行。
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================
您也可以从不同的目录调用该函数,以防您不能或不希望在您正在工作的同一目录中拥有该函数。你可以通过两种方式做到这一点(也许还有更多的选择,但这些是对我有效的方法)。
选择1 临时更改工作目录
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
选择2 将函数所在的目录添加到sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
MathMethod.Py内部。
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
内部Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
输出:1200
方法1。从file.py导入你想要的特定函数:
from file import function
方法2。导入整个文件:
import file as fl
然后,调用file.py中的任何函数,使用:
fl.function(a, b)