[英]How can i reference a variable in one module from another imported module in python?
Menu: 菜单:
import myGame as gameMod
def startGame(screen, level, musicVolume, effectsVolume, numControllers):
game = gameMod.Game()
game.main(screen, level, musicVolume, effectsVolume, numControllers)
myGame: myGame:
class Game(object):
def main(self, screen, level, musicVolume, effectsVolume, numControllers):
self.timer = 0
class EnemyBullet(pygame.sprite.Sprite):
def __init__(self, location, kind, numShots, ID, *groups):
self.dx = math.sin(game.timer) * 100
but this throws an error 但这会引发错误
NameError: global name 'game' is not defined
I'd like for the game.timer to be able to refer to the Game() instance created in Menu even though both EnemyBullet and Game classes are held within the myGame module. 我希望game.timer能够引用Menu中创建的Game()实例,即使EnemyBullet和Game类都保存在myGame模块中。 When the myGame module is run and these lines exist it works out without any errors. 当myGame模块运行并且这些行存在时,它可以正常工作而没有任何错误。 I assume this is because the Game() instance is global and can be found unlike the situation when it's imported. 我认为这是因为Game()实例是全局的,并且与导入时的情况不同,可以找到它。
if __name__ == "__main__":
game = Game()
game.main(screen, 1, 50, 0, 0)
I am not sure what is going on here. 我不确定这是怎么回事。 Didn't you import game as gameMod ? 您不是将游戏导入为gameMod吗? So, shouldn't it be gameMod.timer. 因此,不应该是gameMod.timer。
Now if you are calling timer from within the game module, then why can't you reference it directly as timer. 现在,如果要从游戏模块中调用计时器,那么为什么不能直接将其引用为计时器。 I am assuming that timer is a variable in game and thus exists in its namespace. 我假设计时器是游戏中的变量,因此存在于其命名空间中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.