print('...................') main_actor = '张无忌' main_actress = '赵敏' fan_main_actor = '成昆' fan_main_actress = '周芷若' def light_war(): print(f"{main_actor}破坏了{fan_main_actor}的阴谋诡计") def shaolin_war(): print(f"{main_actor}打败了{fan_main_actress}") def ending(): print(f"{main_actor}和{fan_main_actress}幸福的在一起了") def change(name): global main_actor main_actor = name print("..................."
import sys import yitian as yt # as 给模块重新命名# pycharm报错,模块路径有差异 # sys.path 搜索模块的路径 # print(sys.path) # import yitian # 如果已经到如果该模块,此时则不会再执行模块中的代码了 print(yt.main_actor) # print(main_actor) 报错 当前名称空间中没有main_actor yt.light_war() yt.shaolin_war() yt.ending()
print(globals()) 结果: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000172F298C1D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:/python_workspace_hxt/day24 内置模块 re/yitian.py', '__cached__': None, 'main_actor': '张无忌', 'main_actress': '赵敏', 'fan_main_actor': '成昆', 'fan_main_actress': '周芷若', 'light_war': <function light_war at 0x00000172F2881E18>, 'shaolin_war': <function shaolin_war at 0x00000172F2BFA268>, 'ending': <function ending at 0x00000172F2BFA158>, 'change': <function change at 0x00000172F9C3A400>}
注: 由于模块在导入的时候会创建自己的名称空间,所以在使用模块中的变量的时候一般不会产生冲突
import yitian as yt main_actor = '周游' print(yt.main_actor) # 张无忌 print(main_actor) # 周游
def change(): global fan_main_actress fan_main_actress = '张美欣'
jingyong1.py
import yitian as yt yt.fan_main_actress = '周星娜'
jingyong.py
import yitian as yt import jingyong1 print(yt.fan_main_actress) # 周星娜
1
2
3
|
print (__name__) # 结果为__main__ |
在jinyong.py中
1
2
3
4
5
|
import jinyong1 print (__name__) 结果为 jinyong1 |
import yitian as yt # 导入yitian,但是名字被重命名为yt,就好比变量赋值一样 a = 1 b = a yt.shaoli_war() # 此时可以正常运行 print(globals()) {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002CC30D7C1D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:/python_workspace_hxt/day24 内置模块 re/practice24.py', '__cached__': None, 're': <module 're' from 'C:\\Users\\huxia\\AppData\\Local\\Programs\\Python\\Python36\\lib\\re.py'>, 'sys': <module 'sys' (built-in)>, 'yt': <module 'yitian' from 'F:\\python_workspace_hxt\\day24 内置模块 re\\yitian.py'>}
一次也可以导入多个模块
1
|
import time,random,json,yitian |
# haha.py __all__ = ["money", "eat"] money = 100 def eat(): print("我是吃") def drink(): print("我是呵呵") # test.py from haha import * eat() print(money) drink() # 报错