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>}
注: 因爲模塊在導入的時候會建立本身的名稱空間,因此在使用模塊中的變量的時候通常不會產生衝突 python
import yitian as yt main_actor = '周遊' print(yt.main_actor) # 張無忌 print(main_actor) # 周遊
def change(): global fan_main_actress fan_main_actress = '張美欣'
jingyong1.pyjson
import yitian as yt yt.fan_main_actress = '周星娜'
jingyong.pydom
import yitian as yt import jingyong1 print(yt.fan_main_actress) # 周星娜
print(__name__) # 結果爲__main__
在jinyong.py中ui
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'>}
一次也能夠導入多個模塊spa
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() # 報錯