简体   繁体   English

如何从python中的另一个导入模块引用一个模块中的变量?

[英]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.

相关问题 Python:为什么导入的模块不能引用另一个导入的模块? - Python: why can't an imported module reference another imported module? 如何将一个模块变量传递给 python 中的另一个模块? - How can i pass one module variable to another module in python? 如何使用 Python 脚本将指针变量从一个 cython 模块传输到另一个模块 - How can I transfer a pointer variable from one cython module to another using a Python script 如何阻止Python stdlib模块导入? - How can I block a Python stdlib module from being imported? Python-如何在导入为“ from module import *”的模块中更改变量 - Python - How to alter variable in a module imported as “from module import *” 如何在python中取消缓存导入的模块? - How can I uncache imported module in python? 如何从 URL 导入 Python 模块? - How can a Python module be imported from a URL? 在Python中,如何从导入的模块访问主模块的名称空间? - In Python, how can I access the namespace of the main module from an imported module? 为什么我可以在 python 中从另一个模块访问一个模块中的非全局变量? - Why can I access a non-global variable in one module from another in python? 为什么要使用python中的导入模块引用导入的模块 - Why can you reference an imported module using the importing module in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM