設置特殊變量,如__name__;css
執行源代碼文件中的全部代碼;python
print("before import")import math
print("before functionA")def functionA(): print("Function A")
print("before functionB")def functionB(): print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")if __name__ == '__main__': functionA() functionB()print("after __name__ guard")
python foo.py
__name__ = "__main__"
import foo
__name__ = "foo"
before importbefore functionAbefore functionBbefore __name__ guardFunction AFunction B 10.0after __name__ guard
before importbefore functionAbefore functionBbefore __name__ guardFunction AFunction B 10.0after __name__ guard
before importbefore functionAbefore functionBbefore __name__ guardafter __name__ guard
import fooprint('current module')
before importbefore functionAbefore functionBbefore __name__ guardafter __name__ guardcurrent module
# foo2.pydef functionA(): print("a1") import foo2 print("a2") functionB() print("a3")
def functionB(): print("b")
print("t1")if __name__ == "__main__": print("m1") functionA() print("m2")print("t2")
t1m1a1t1t2a2ba3m2t2
# foo3.pydef functionA(): print("a1") import foo3 print("a2") functionB() print("a3")
def functionB(): print("b")
print("t1")print("m1")functionA()print("m2")print("t2")
t1m1a1t1m1a1a2ba3m2t2a2ba3m2t2
一、連Python產生器(Generator)的原理都解釋不了,還敢說Python用了5年?nginx
二、牛掰了!鴻蒙與Android完美融合,將鴻蒙設備當Android設備用web
四、【鴻蒙學院】鴻蒙IDE:下載、安裝DevEco Studioswift
關注「極客起源」公衆號,加星標,不錯過精彩技術乾貨
app
本文分享自微信公衆號 - 極客起源(geekculture)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。編程語言