pygame.display.get_surface() 作为 func 中的默认参数等于 None,但在 func 中命令 returns 值

pygame.display.get_surface() as default param in func equals None, but in a func the command returns value

当我将 pygame.display.get_surface() 作为 func 中的默认参数时,它会给我 None,示例:

def func(surface = pygame.display.get_surface()):
    print(surface)

然后我得到 None。

但是如果我这样做:

def func():
    print(pygame.display.get_surface())

它会打印出它的详细信息(例如:Surface(800x600x32 SW))

它发生的原因是什么?

def func(surface=pygame.display.get_surface()):
    print(surface)

这会在 定义 函数时调用 pygame.display.get_surface(),而不是在调用时调用。

创建函数本身时,您还没有初始化 pygame,所以 pygame.display.get_surface() returns None.

如您所见,另一种方法是将 get_surface() 调用从函数定义移动到函数体:

def func(surface=None):
    if surface is None:
         surface = pygame.display.get_surface()
    print(surface)