28. Several ways to import python modules

For module reference, we need to create two files, one module file and one running test file.

# 模块文件 myMod.py
print("in my mod")

def modFunc():
    print("function modfunc")
    
class MyMod():
    def __init__(self):
        print("Create MyMod")

# 测试文件 testModule.py
print("Test Module")
# 导入模块
import myMod
# import myMod # 多次导入模块并不会执行两次,模块中的代码只会被执行一次
myMod.modFunc()
obj = myMod.MyMod()

Operation result:
Insert picture description here
When you import the module name, the module will be executed. If you import the module multiple times, the code in the module will not be executed twice, the code in the module will only be executed once.

Another way to import modules:

# 测试文件 testModule.py
print("Test Module")
# 通过from 将模块中的函数和类引入当前命名空间
from myMod import modFunc
modFunc()

# 导入模块中的所有内容
from myMod import *
obj = MyMod()

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/zhaopeng01zp/article/details/109303142