The value of knowledge lies not in possession, but in share.

0%

Python--目录间.py文件调用

这里对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
# a.py
def show():
print("this is a.py")
1
2
3
4
5
6
7
8
9
10
# b.py
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
# hello.py
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()

🍭支持一根棒棒糖吧!