import sys
sys.path.append(r'E:\PythonProject\winycg')
'''python import模块时, 是在sys.path里按顺序查找的。
sys.path是一个列表,里面以字符串的形式存储了许多路径。
使用A.py文件中的函数需要先将他的文件路径放到sys.path中'''
import A
a=A.A(2,3)
a.add()
在同一个文件夹下调用函数:A.py文件:def add(x,y): print('和为:%d'%(x+y))B.py文件:import AA.add(1,2)或from A import addadd(1,2)调用类:A.py文件:class A: def __init__(self,xx,yy): self.x=
文章目录一、引入同一目录下的
py
文件
二、引入不同目录下的
文件
1、
调用
子目录下的
文件
2、导入上级目录下的
文件
关于 _ _ init_ _.
py
在写
python
程序的时候,经常会用到引用其他的.
py
文件
,如何使用import进行引入,下面将进行介绍:
一、引入同一目录下的
py
文件
如下图,main.
py
和deeplabv2.
py
在同
一个
文件
夹内
-|model
-|deeplabv2.
py
-|main.
py
如果想在main.
py
文件
内引入d.
os.system("
python
file_B.
py
para_a1 para_a2")
#其他形式
os.system("
python
file_B.
py
%s" % para_A)
os.system("
python
file_B.
py
" + para_A)
需要注意
文件
路径的写法,因为我是在docker
中
运行
文件
,
文件
名前面需要加/,如os.system("
python
/file_B.
py
")
Python
调用
其他的.
py
文件
中
的
类
和
函数
Python
调用
其他的.
py
文件
中
的
类
和
函数
A与B在同
一个
文件
夹的
调用
方式1.
调用
函数
2.
调用
类
A与B不在同
一个
文件
夹的
调用
方式
Python
调用
其他的.
py
文件
中
的
类
和
函数
有时为了避免重复写其他.
py
文件
中
已经存在的
类
或
函数
,需要在某个
python
文件
(下面称为B
文件
)
中
调用
已经编辑好的
python
文件
(下面称A
文件
)
中
的
类
或
函数
,下面介绍下如何实现...
1. 使用import语句
如果你想在
一个
Python
脚本
中
使用另
一个
Python
脚本
中
的
函数
或变量,可以使用import语句。假设你有两个
Python
文件
:file1.
py
和file2.
py
,其
中
file2.
py
包含了
一个
函数
add_numbers:
# file2.
py
def add_numbers(a, b):
return a + b
你可以在file1.
py
中
使用这个
函数
,只需要在file1.
py
中
添加如下import语句:
# file1.
py
import file2
result = file2.add_numbers(2, 3)
print(result)
这里,我们使用了import语句将file2.
py
中
的
函数
add_numbers引入到file1.
py
中
,然后在file1.
py
中
直接
调用
这个
函数
。
2. 使用from...import语句
如果你只想引入
一个
Python
文件
中
的某个
函数
或变量,可以使用from...import语句。这个语法可以让你从
一个
Python
文件
中
只引入你需要的
函数
或变量,而不是引入整个
文件
。以下是
一个
例子:
# file1.
py
from file2 import add_numbers
result = add_numbers(2, 3)
print(result)
这里,我们使用了from...import语句,将file2.
py
文件
中
的add_numbers
函数
引入到file1.
py
中
,然后在file1.
py
中
直接
调用
这个
函数
。
这两种方法都可以用来实现在
一个
Python
脚本
中
调用
另
一个
Python
脚本
中
的
函数
或变量,具体使用哪种方法取决于你的具体需求。