1. import
import用于导入模块中的所有内容。
新建hello.py以及import_hello.py 两个文件放在同一目录下,用于观察:
# hello.py
a = 10
print("Hello World")
def hello_python():
print("Hello Python")
# import_hello.py
import hello # 导入hello.py中的所有内容
hello.hello_python() # 调用hello.py中的hello_python()函数
print(hello.a) # 输出hello.py中的a变量


2. from…import
from...import用于导入模块中的部分内容,这部分内容便可直接使用,而不需要通过模块名.变量或者模块名.函数去使用。
新建hello.py以及import_hello.py 两个文件放在同一目录下,用于观察:
# hello.py
a = 10
print("Hello World")
def hello_python():
print("Hello Python")
# import_hello.py
# 导入hello.py中的变量a 和 hello_python函数
from hello import a, hello_python
hello_python() # 可直接调用hello_python()
print(a) # 可直接使用变量a

3. if __name__ == “__main__”
if __name__ == "__main__":中的代码,作为脚本直接执行时会生效,作为模块导入到其他文件时,不会生效。
新建hello.py以及import_hello.py 两个文件放在同一目录下,用于观察:
# hello.py
# 1.作为脚本直接执行
# 2.作为模块导入到 import_hello.py中
print("Hello World")
if __name__ == "__main__":
print("Hello Python")
# import_hello.py
import hello
1.作为脚本直接执行

2.作为作为模块导入到其他文件中

本文介绍了Python中import、from...import以及if __name__ == __main__的用法。import用于导入整个模块,from...import则能选择性导入模块内的特定内容,直接使用。if __name__ == __main__确保代码仅在直接运行模块时执行,而非被其他模块导入时。通过示例展示了这些语法的实际应用。
6247

被折叠的 条评论
为什么被折叠?



