使用 import 语句导入模块
使用 import 语句导入模块是使用模块最常见的方式。这使得模块中的所有代码都可以供你当前的脚本使用。
在文件浏览器中,你会找到一个名为 main.py 的空文件。这将是我们本次实验其余部分的主脚本。
打开 main.py 并添加以下行来导入 hello 模块:
import hello
print("The main.py script has finished.")
保存文件。现在,从终端运行 main.py:
python3 main.py
仔细观察输出:
This code runs on import or direct execution.
The main.py script has finished.
注意,只有来自 hello.py 的第一条 print 语句被执行了。if __name__ == "__main__": 块中的代码被跳过了。这是因为当 main.py 导入 hello 时,在 hello.py 上下文中的 __name__ 变量被设置为 "hello"(模块的名称),而不是 "__main__"。此功能对于创建在导入时不会产生不必要副作用的可重用模块至关重要。
现在,让我们处理一个包含多于打印语句的模块。打开 module_a.py 文件。它包含一个变量、一个函数和一个类。
PI = 3.14159
def greet(name):
print(f"Hello, {name} from module_a!")
class Calculator:
def add(self, x, y):
return x + y
修改 main.py 以导入 module_a 并使用其成员。要访问导入模块的成员,你使用语法 module_name.member_name。
将 main.py 的内容替换为以下内容:
import module_a
## Access the PI variable
print(f"The value of PI is {module_a.PI}")
## Call the greet function
module_a.greet("LabEx")
## Create an instance of the Calculator class and use its method
calc = module_a.Calculator()
result = calc.add(5, 3)
print(f"5 + 3 = {result}")
保存文件并运行它:
python3 main.py
输出将是:
The value of PI is 3.14159
Hello, LabEx from module_a!
5 + 3 = 8
这演示了 import 语句如何加载整个模块,以及你如何使用模块名作为前缀来访问其内容。