【问题标题】:mixing up pygame.time() and time.time()混合 pygame.time() 和 time.time()
【发布时间】:2017-04-06 09:11:30
【问题描述】:

对于我正在使用time.time() 的扫雷游戏,我同时导入了timepygame。这是我的错误报告

line 5, in save_score
    end = time.time()
AttributeError: module 'pygame.time' has no attribute 'time'

这里有我确实导入了 time 和 pygame 的证据:

import sys, math, time
def save_score(name, size, mine):
    end = time.time()
~
from pygame import *

如果有人能解释如何避免/修复此错误,将不胜感激。

【问题讨论】:

标签: python python-3.x time pygame


【解决方案1】:

由于您的线路,您遇到了命名空间冲突:

from pygame import *

这会污染你的全局命名空间,因为你可以从 pygame 导入所有内容。它让懒惰的生活变得轻松——你不必引用特定的命名空间来使用 pygame 的函数。但它也有一些不好的后果。

在这种情况下,您已将“时间”作为模块导入到全局命名空间中。当你像从 pygame 一样导入时,它有一个名为 time 的子模块。 pygame.time 替换您的常规时间模块。

解决这个问题的方法是正确使用模块/命名空间。

一种方法是,不要使用from pygame import *,而是使用:

import pygame

但是你必须将 pygame 放在对 pygame 函数或模块的每个引用之前。这通常很好,这样您和阅读您代码的任何其他人都知道您正在调用什么函数。

你可以稍微缩写一下,使用import ... as

import pygame as pg

那么,您将不做pygame.time 之类的事情,而是做pg.time

如果您想专门将某些内容放入全局命名空间中,您可以执行以下操作:

from pygame import foo

from pygame import time as pygt

但如果你这样做from pygame import timefrom pygame import *,pygame 的时间会覆盖其他时间模块。

【讨论】:

    猜你喜欢
    • 2017-06-25
    • 2018-06-20
    • 2015-12-04
    • 2021-11-29
    • 1970-01-01
    • 2013-06-22
    • 2012-04-17
    • 2010-09-16
    • 2017-05-18
    相关资源
    最近更新 更多