Python 模块初始化的时候,发生了什么?
假設(shè)有一個 hello.py 的模塊,當(dāng)我們從別的模塊調(diào)用 hello.py 的時候,會發(fā)生什么呢?
方便起見,我們之間在 hello.py 的目錄下使用 ipython 導(dǎo)入了。
hello.py 的代碼如下,分別有模塊變量,函數(shù),類變量,類的靜態(tài)方法、類方法和實(shí)例方法。
# hello.py print 'module value' module_a = 233def f():print 'func name:', f.__name__class DoClass(object):print 'do class'c_value = 88@classmethoddef cf(cls):print 'cf', cls.cf@staticmethoddef sf():print 'sf', DoClass.sf.func_namedef f(self):print self.f在 hello.py 的目錄下,開啟 ipython,查看結(jié)果。
In [1]: import sysIn [2]: sys.modules['hello'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-2-ec73143594c2> in <module>() ----> 1 sys.modules['hello']KeyError: 'hello'在還沒有導(dǎo)入 hello 模塊的時候,可以看到,此時系統(tǒng)中是沒有這個模塊的,讓我們進(jìn)行一次導(dǎo)入。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' In [3]: import hello module value do classIn [4]: sys.modules['hello'] Out[4]: <module 'hello' from 'hello.pyc'>導(dǎo)入后,可以看到模塊中的模塊變量和類變量都直接執(zhí)行了,并且可以看到此時系統(tǒng)中是有了 hello 這個模塊了。此時可以看一下 hello 模塊的屬性:
In [5]: dir(hello) Out[5]: ['DoClass','__builtins__','__doc__','__file__','__name__','__package__','f','module_a']可以看到,模塊有模塊變量、函數(shù)以及類三個屬性。此時,在 ipython 中再次導(dǎo)入 hello,查看結(jié)果:
In [6]: import helloIn [7]:發(fā)現(xiàn)此時什么都沒有輸出,這是因?yàn)槟K只有第一次被導(dǎo)入的時候才會被執(zhí)行。其實(shí),可以把導(dǎo)入模塊作為生成一個新的對象,模塊變量和類變量都是在模塊對象初始化的時候執(zhí)行的,而函數(shù)和類的方法,則不會初始化的時候執(zhí)行,只有在調(diào)用的時候才會執(zhí)行:
In [7]: hello.f() func name: fIn [8]: hello.module_a Out[8]: 233In [9]: hello.DoClass Out[9]: hello.DoClassIn [10]: hello.DoClass.c_value Out[10]: 88那么,如果在你模塊中導(dǎo)入了其他的模塊,或者導(dǎo)入了其他模塊的方法,又是怎樣的呢?
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' # hello.py # -*- coding: utf-8 -*- import math from math import sqrt在模塊中導(dǎo)入 math 以及 math 的 sqrt 方法,然后導(dǎo)入 hello:
In [1]: import helloIn [2]: dir(hello) Out[2]: ['__builtins__','__doc__','__file__','__name__','__package__','math','sqrt']In [3]: hello.math Out[3]: <module 'math' from '/usr/local/Cellar/python/2.7.14_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'>In [4]: hello.math.sqrt(100) Out[4]: 10.0In [5]: hello.sqrt(1000) Out[5]: 31.622776601683793可以看到,導(dǎo)入 hello 后,在 hello 中導(dǎo)入的 math 以及 sqrt 都成了 hello 的方法,這和我們直接在模塊中定義的變量是一致的。
總結(jié):不管在模塊中導(dǎo)入其他的模塊或者直接定義變量,函數(shù)以及類,擋在別的模塊中導(dǎo)入該模塊的時候,這些內(nèi)容都將成為該模塊的屬性。這其實(shí)和 Python 中一切皆對象是保持一致的。
總結(jié)
以上是生活随笔為你收集整理的Python 模块初始化的时候,发生了什么?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python小练习:批量删除多个文件夹内
- 下一篇: Python-函数和代码复用