这里对Python各种目录之间的.py文件调用做一个归纳。
1 2 3 4 5 6 7 8 9
| . └── folder ├── data │ └── data.txt | └── abc.py └── test | └── a.py | └── b.py └── hello.py
|
1 2 3
| def show(): print("this is a.py")
|
1 2 3 4 5 6 7 8 9 10
| def add(x,y): print("sum = "%(x+y)) class B: def __init__(self, xx, yy): self.x = xx self.y = yy def plus(self): print("sum = "%(self.x + self.y))
|
1 2 3
| def showHello(): print("this is hello.py")
|
父目录调用子目录.py文件
1 2 3 4 5 6 7 8 9
| . └── folder ├── data │ └── data.txt | └── abc.py └── test | └── a.py | └── b.py └── hello.py
|
譬如:hello.py
调用b.py
,需要test目录下创建__init__.py
文件(该文件可以什么都不写)
1 2 3 4 5 6 7
| import test.b test.b.add(2,3)
from test.b import add add(2,3)
|
同目录调用.py文件
1 2 3 4 5 6 7 8 9
| . └── folder ├── data │ └── data.txt | └── abc.py └── test | └── a.py | └── b.py └── hello.py
|
譬如: a.py
调用b.py
调用函数:
1 2 3 4 5 6 7
| import b b.add(2,3)
from b import add add(2,3)
|
调用类:
1 2 3 4 5 6 7 8 9
| import b xyz = b.B(2,3) xyz.plus()
from b import B; xyz = B(2,3) xyz.plus()
|
跨目录读取.py文件
子目录调用父目录.py文件
1 2 3 4 5 6 7 8 9
| . └── folder ├── data │ └── data.txt | └── abc.py └── test | └── a.py | └── b.py └── hello.py
|
abc.py
调用hello.py
:
1 2 3 4 5 6 7 8 9 10 11
| import sys sys.path.append("..") import hello hello.showHello()
import sys sys.path.append("..") from hello import showHello showHello()
|
不同子目录.py文件互相调用
1 2 3 4 5 6 7 8 9
| . └── folder ├── data │ └── data.txt | └── abc.py └── test | └── a.py | └── b.py └── hello.py
|
abc.py
调用a.py
:
1 2 3 4 5 6 7 8 9 10 11
| import sys sys.path.append("../test") import a a.show()
import sys sys.path.append("../test") from a import show show()
|