8

我是一个非常缺乏经验的程序员,我创建一个游戏(使用 Python 3.3)作为学习练习。我目前有一个主模块和一个战斗模块。

游戏中的人由“Person”类的实例表示,并在主模块中创建。但是,战斗模块显然需要访问这些对象。此外,我稍后可能会创建更多模块,这些模块也需要访问这些对象。

如何允许其他模块从 main.py 访问 Persons?

就目前而言, main.py 有

import combat

在顶部; 添加

import main

战斗.py 似乎没有帮助。

我应该在一个单独的模块(common.py?)中实例化我的对象并将它们导入到需要访问它们的每个模块中吗?

4

2 回答 2

10

是的,您绝对应该考虑到这一点。您尝试的是模块之间的循环导入,这可能会带来很大的问题。如果combatimportsmainmainimports combat,那么你可能会得到一个异常,因为在开始执行导入main时还没有完成执行。combat假设main是您的启动脚本,它可能只是实例化一个类或从另一个模块调用一个方法。也避免使用全局变量。即使现在看起来它们不会成为问题,但以后可能会在后面咬你。

也就是说,您可以像这样引用模块的成员:

import common
x = common.some_method_in_common()
y = common.SomeClass()

或者

from common import SomeClass
y = SomeClass()

就个人而言,我通常避免在没有使用模块名称限定的情况下引用来自另一个模块的方法,但这也是合法的:

from common import some_method_in_common
x = some_method_in_common()

我通常from ... import ...用于类,我通常将第一种形式用于方法。(是的,这有时意味着除了导入模块本身之外,我还从模块导入了特定的类。)但这只是我个人的约定。

强烈建议不要使用另一种语法是

from common import *
y = SomeClass()

这会将 common 的每个成员导入当前范围,但不以下划线 ( _) 开头。我不鼓励它的原因是因为它使理解名称的来源并且使破坏事情变得太容易了。考虑这对导入:

from common import *
from some_other_module import *
y = SomeClass()

来自哪个模块SomeClass?除了去看看这两个模块之外,没有别的办法。更糟糕的是,如果两个模块都定义SomeClassSomeClass稍后添加到some_other_module?

于 2013-03-01T22:43:53.913 回答
1

if you have imported main module in combat module by using import main, then you should use main.*(stuff that are implemented in main module) to access classes and methods in there.

example:

import main

person = main.Person()

also you can use from main import * or import Person to avoid main.* in the previous.

There are some rules for importing modules as described in http://effbot.org/zone/import-confusion.htm :

  1. import X imports the module X, and creates a reference to that module in the current namespace. Or in other words, after you’ve run this statement, you can use X.name to refer to things defined in module X.
  2. from X import * imports the module X, and creates references in the current namespace to all public objects defined by that module (that is, everything that doesn’t have a name starting with “_”). Or in other words, after you’ve run this statement, you can simply use a plain name to refer to things defined in module X. But X itself is not defined, so X.name doesn’t work. And if name was already defined, it is replaced by the new version. And if name in X is changed to point to some other object, your module won’t notice.
  3. from X import a, b, c imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.
  4. Finally, X = __import__(‘X’) works like import X, with the difference that you

    1) pass the module name as a string, and

    2) explicitly assign it to a variable in your current namespace.

于 2013-03-01T22:46:30.217 回答