pygame的init究竟做了什么


當我們在init()的時候,我們在干什么

init 這個單詞在我們用python進行面向對象開發的時候是跑不了的。理解python的__init__其實就是和這里的init作用差不多。做的工作都是__初始化__.

在和孩子解釋這個概念的時候,我的理解還是,保持它的專業性,告訴他們這個專有名詞——初始化(initialize vt.)。至於他在干什么,我的解釋是這樣的:

我們已經知道python有一個特殊的“工具包(模塊)”叫pygame了。在我們要動手用它完成我們的想法之前,電腦這個強迫症需要我們檢查一遍,這個工具包是否完整,能否正常給我們提供幫助。而這個檢查的動作,就是pygame.init()

那么init()實際上檢查了哪些東西呢?

這個其實也不難實驗。直接在shell里面,我執行了這個函數:

>>> import pygame
>>> pygame.init()
(6, 0)

不明所以的,他給了我一個元組(6,0),我也很不理解,這個6和0分別代表什么意思。所以查閱了pygame的官方文檔

initialize all imported pygame modules

init() -> (numpass, numfail)

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. The init() functions for individual modules will raise exceptions when they fail.

You may want to initialize the different modules separately to speed up your program or to not use things your game does not.

It is safe to call this init() more than once: repeated calls will have no effect. This is true even if you have pygame.quit() all the modules.

初始化所有導入的pygame模塊。如果模塊失敗,則不會引發異常,但如果成功且失敗的總數將作為元組返回。您可以隨時手動初始化單個模塊,但pygame.init()初始化所有導入的pygame模塊是一種方便的方法來啟動所有內容。各個模塊的init()函數會在失敗時引發異常。

您可能希望單獨初始化不同的模塊以加速您的程序或不使用您的游戲沒有的東西。

不止一次調用此init()是安全的:重復調用將不起作用。即使你有pygame.quit()所有模塊也是如此。

關於init()的一個意外的實驗

我以前從來沒有深究過pygame.init()這個函數究竟init了哪些模塊,僅僅在實踐的過程中知道,音頻播放和創建文字字體的時候,如果沒有init就會報錯。

今天我在安裝我的新的電腦環境的時候,因為不知道電腦的型號,所以並沒有特意去搜索和安裝電腦對應的驅動。結果在安裝完python之后,安裝pygame(wheel也要安裝)之后,運行常規的測試函數pygame.init()返回的數字是(5,1)

排除問題的方法就是把已知可以init()的子模塊都先運行掉。經過排查,發現pygame無法調用聲卡驅動。剩下的事情就好辦很多了,重新安裝一下聲卡驅動,重啟之后就可以正常init了。

但是在這個過程中,我可以得出比以前更加接近實際的一個結論:

pygame.init()在做的,其實就是檢查,電腦上一些需要的硬件調用接口、基礎功能是否有問題。如果有,他會在程序運行之前就反饋給你,方便你進行排查和規避。

說了這么多,它到底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

 

 

---------------------------------------------------------------------摘取自sc0T7_ly的博客-----------------------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM