【pygame】pygame的init()

你究竟有(init)几个好(子)妹(模)妹(块)?python

当咱们在init()的时候,咱们在干什么

init 这个单词在咱们用python进行面向对象开发的时候是跑不了的。理解python的__init__其实就是和这里的init做用差很少。作的工做都是__初始化__.shell

在和孩子解释这个概念的时候,个人理解仍是,保持它的专业性,告诉他们这个专有名词——初始化(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)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. The init() functions for individual modules will raise exceptions when they fail.this

You 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 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

我把pygame官网上面的doc里介绍的全部带有init的子模块都运行了一遍。其中midi和freetype这两个模块已经没有了(吐槽一下官方的文档吧,都没了还放着嘛)。最后一个scrap初始化是由于没有窗口。这样的话,其实已经有5个模块是被初始化了。可是scrap在没有窗口的状况下会报错,到底算不算一个init。还须要后面再仔细看看文档和源码吧。

相关文章
相关标签/搜索