返回博客列表

Python 中模块导入

2026-01-29
1 min read
python

1. 在 python 中一个文件就是一个模块 2. 同目录下文件可以直接引用到 3. 非同目录下导入要用包,在目录下写 文件,这样在导入包的之后会先执行 注意使用.表示是当前目录下的文件 4. 经过上面操作就可以在外面目录正常使用了。

  1. 在 python 中一个文件就是一个模块
python
def add(a, b):
    return a + b

def secret_function():
    return "This is secret"
PI = 3.14159

# 只影响 form mytools import *
# 不影响 from mytools import PI,add,secret_function
__all__ = ['add', 'secret_function','PI']
  1. 同目录下文件可以直接引用到
python
import mytools
# form mytools import *
result = mytools.add(2, 3)
print(result)
print(mytools.PI)
  1. 非同目录下导入要用包,在目录下写 __init__.py 文件,这样在导入包的之后会先执行__ini__.py
language
├── PyTest.py
├── __init__.py
└── mytools.py

注意使用.表示是当前目录下的文件

python
from .mytools import *
  1. 经过上面操作就可以在外面目录正常使用了。
python
import py
print(py.add(1, 2))
print(py.PI)
-----------------------------
from py import *
print(add(1, 2))
print(PI)
返回博客列表
最后更新于 2026-01-29
想法或问题?在 GitHub Issue 下方参与讨论
去评论