# other.py
slogan ='带你打开编程世界的大门'print(slogan)# main.pyimport other # 导入 other 模块# 输出:带你打开编程世界的大门*********************分割线************************# other.py
slogan ='带你打开编程世界的大门'defrepeat_slogan():return slogan *2# main.pyimport other # 导入 other 模块print(other.slogan)# 输出:带你打开编程世界的大门print(other.repeat_slogan())# 输出:带你打开编程世界的大门带你打开编程世界的大门
导入模块时也可以只导入某个模块中我们需要的那一部分from 模块 import 变量(函数)
# other.py
slogan ='带你打开编程世界的大门'defrepeat_slogan():return slogan *2# main.pyfrom other import slogan # 从 other 模块导入 sloganprint(slogan)# 输出:带你打开编程世界的大门print(other.repeat_slogan())# 报错:NameError: name 'other' is not defined on line 6# 使用 from ... import ... 的方式导入就不能再用 other. 的方式访问模块内的变量或函数
# xxx.py
代码块 A
if __name__ =='__main__':
代码块 B
# 当直接运行xxx.py文件时,执行代码块 A,并执行代码块 B#当xxx.py文件被import时,只执行代码块 A,不执行代码块 B#实例:# other.pyprint('我是 other 模块')if __name__ =='__main__':print('我被直接运行了(other)')# main.pyimport other
print('我是 main 模块')if __name__ =='__main__':print('我被直接运行了(main)')
结果:
我是 other 模块
我是 main 模块
我被直接运行了(main)