python3精要(35)-模块(1)-import
生活随笔
收集整理的這篇文章主要介紹了
python3精要(35)-模块(1)-import
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
from和import 導(dǎo)入模塊
import 讀取整個模塊,而from只導(dǎo)入模塊中的某些變量和函數(shù)
import導(dǎo)入時,被導(dǎo)入模塊的全部頂層變量和語句將被執(zhí)行
# -*- coding: utf-8 -*- """ Created on Sat Jan 23 13:54:16 2021@author: Administrator """ x=11 y=22 def testfun2():print("testfun2") def testfun1():print("testfun1")print("testmodule importing...")#if __name__ == "__main__": # print("testmodule runing...") # testfun1() # testfun2() # -*- coding: utf-8 -*- """ Spyder EditorThis is a temporary script file. """ import testmodule print(testmodule.x) testmodule.testfun1() print(testmodule.__name__) print(__name__) runfile('G:/learn/2.py', wdir='G:/learn') testmodule importing... 11 testfun1 testmodule __main__被導(dǎo)入 模塊也可以直接執(zhí)行
runfile('G:/learn/testmodule.py', wdir='G:/learn') testmodule importing...通過Python中的if name == 'main’形式識別 是被導(dǎo)入 的還是直接執(zhí)行的
下面是直接執(zhí)行的
下面是導(dǎo)入的
runfile('G:/learn/2.py', wdir='G:/learn') testmodule importing... 11 testfun1 testmodule __main__被導(dǎo)入的__name__為模塊名,當(dāng)前執(zhí)行的__name__為__main__
將被導(dǎo)入模塊改為:
因此,被導(dǎo)入模塊可改成以下形式,效果一樣
# -*- coding: utf-8 -*- """ Created on Sat Jan 23 13:54:16 2021@author: Administrator """ x=11 y=22 def testfun2():print("testfun2") def testfun1():print("testfun1")if __name__ == "testmodule":print("testmodule importing...") else:print("testmodule runing...")testfun1()testfun2() runfile('G:/learn/testmodule.py', wdir='G:/learn') testmodule runing... testfun1 testfun2runfile('G:/learn/2.py', wdir='G:/learn') testmodule importing... 11 testfun1 testmodule __main__總結(jié)
以上是生活随笔為你收集整理的python3精要(35)-模块(1)-import的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工业用微型计算机笔记(3)-存储单位与基
- 下一篇: c++计算机等级考试笔记(1)