你究竟有(init)幾個好(子)妹(模)妹(塊)?python
init
這個單詞在咱們用python進行面向對象開發的時候是跑不了的。理解python的__init__
其實就是和這裏的init做用差很少。作的工做都是__初始化__.shell
在和孩子解釋這個概念的時候,個人理解仍是,保持它的專業性,告訴他們這個專有名詞——初始化(initialize vt.)。至於他在幹什麼,個人解釋是這樣的:安全
咱們已經知道python有一個特殊的「工具包(模塊)」叫pygame了。在咱們要動手用它完成咱們的想法以前,電腦這個強迫症須要咱們檢查一遍,這個工具包是否完整,可否正常給咱們提供幫助。而這個檢查的動做,就是
pygame.init()
函數
這個其實也不難實驗。直接在shell裏面,我執行了這個函數:工具
>>> import pygame >>> pygame.init() (6, 0)
不明因此的,他給了我一個元組(6,0)
,我也很不理解,這個6和0分別表明什麼意思。因此查閱了pygame的官方文檔測試
initialize all imported pygame modules字體
init() -> (numpass, numfail)ui
Initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but
pygame.init()
is a convenient way to get everything started. Theinit()
functions for individual modules will raise exceptions when they fail.thisYou may want to initialize the different modules separately to speed up your program or to not use things your game does not.code
It is safe to call this
init()
more than once: repeated calls will have no effect. This is true even if you havepygame.quit()
all the modules.初始化全部導入的pygame模塊。若是模塊失敗,則不會引起異常,但若是成功且失敗的總數將做爲元組返回。您能夠隨時手動初始化單個模塊,但pygame.init()初始化全部導入的pygame模塊是一種方便的方法來啓動全部內容。各個模塊的init()函數會在失敗時引起異常。
您可能但願單獨初始化不一樣的模塊以加速您的程序或不使用您的遊戲沒有的東西。
不止一次調用此init()是安全的:重複調用將不起做用。即便你有pygame.quit()全部模塊也是如此。
我之前歷來沒有深究過pygame.init()
這個函數究竟init了哪些模塊,僅僅在實踐的過程當中知道,音頻播放和建立文字字體的時候,若是沒有init就會報錯。
今天我在安裝個人新的電腦環境的時候,由於不知道電腦的型號,因此並無特地去搜索和安裝電腦對應的驅動。結果在安裝完python以後,安裝pygame(wheel也要安裝)以後,運行常規的測試函數pygame.init()
返回的數字是(5,1)
排除問題的方法就是把已知能夠init()
的子模塊都先運行掉。通過排查,發現pygame沒法調用聲卡驅動。剩下的事情就好辦不少了,從新安裝一下聲卡驅動,重啓以後就能夠正常init了。
可是在這個過程當中,我能夠得出比之前更加接近實際的一個結論:
pygame.init()
在作的,其實就是檢查,電腦上一些須要的硬件調用接口、基礎功能是否有問題。若是有,他會在程序運行以前就反饋給你,方便你進行排查和規避。
>>> import pygame >>> pygame.init() (6, 0) >>> pygame.display.init() >>> pygame.font.init() >>> pygame.joystick.init() >>> pygame.mixer.init() >>> pygame.freetype.init() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'pygame' has no attribute 'freetype' >>> pygame.midi.init() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'pygame' has no attribute 'midi' >>> pygame.cdrom.init() >>> pygame.scrap.init() Traceback (most recent call last): File "<stdin>", line 1, in <module> pygame.error: No display mode is set
我把pygame官網上面的doc裏介紹的全部帶有init的子模塊都運行了一遍。其中midi和freetype這兩個模塊已經沒有了(吐槽一下官方的文檔吧,都沒了還放着嘛)。最後一個scrap初始化是由於沒有窗口。這樣的話,其實已經有5個模塊是被初始化了。可是scrap在沒有窗口的狀況下會報錯,到底算不算一個init。還須要後面再仔細看看文檔和源碼吧。