在Python中,调用多个文件中的函数或类可以通过以下几种方法实现:
1. 使用`import`语句:
```python
file1.py
def func1():
print("Hello from file1")
file2.py
import file1
file1.func1() 调用file1.py中的func1函数
2. 使用`from...import`语句:
```python
file1.py
def func1():
print("Hello from file1")
file2.py
from file1 import func1
func1() 调用file1.py中的func1函数
3. 使用相对路径导入:
```python
file1.py
def func1():
print("Hello from file1")
file2.py
import sys
sys.path.append('/path/to/directory') 添加文件所在目录到sys.path
import file1
file1.func1() 调用file1.py中的func1函数
4. 使用`if __name__ == '__main__':`来确保只在直接运行文件时执行函数或类:
```python
file1.py
def func1():
print("Hello from file1")
file2.py
from file1 import func1
if __name__ == '__main__':
func1() 调用file1.py中的func1函数