开发者

Using Pygame Module from imported script

Greetings! I'm creating a simple snake game. I want to expand my classes in different modules e.i. have menu class in a separate script from my main game loop. In other words, I want my imported script to take the pygame init which was called earlier in main script.

Here is a quick example using pseudo code of my problem:

one.py

def version():
    print pygame.version

In main.py i have imported pygame and did pygame.init(). From here, I also want to use the def version() from one.py

main.py

import pygame
import one

pygame.init()

one.version()

However, it gives me the no pygame defined error. I know the reason why it give me an error is because when the one.py is called from within the main.py, it doesnt retain the declarat开发者_JS百科ions from main.py.

What I want to know is a method to doing the mentioned above that will actually work.

Thank you!


The imports of the module that imports module X don't leak through to X's namespace (which is a good thing - it would either require dynamic scoping or C/C++-style #include, both are almost never useful and often even harmful). It's a completely seperate namespace on its own. If you want to use something (e.g. pygame) in a module (e.g. one), import it there.


Python's import model is the following: If you need module a.b.c in your module d.e.f, then add an import a.b.c (or similar) to the beginning of d/e/f.py. (This is similar to how Java's import works.) So if you have many modules (e.g. d.e.f1, d.e.f2, ...) which need many modules (e.g. a.b.c1, a.b.c2, ...), then you should import each required module from each of your modules, resulting multiple copies of the same import statement in your module source files. It looks like that a more compact import model (where you have to import the same module only once) would be better, but that has a very important disadvantage: the compact import model would use a global namespace, and it would make dependency tracking (e.g. who needs this code?, where does this code come from?) much harder. So every time you write an import line which you think is not necessary, remember that this is the (small) price you're paying for maintainable code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜