【发布时间】:2015-02-08 14:52:17
【问题描述】:
如何将对象导入类的命名空间并使其可用于每个函数?假设我在 terrain.py 中有一个名为 terrain 的单例对象,我希望游戏中的所有生物都了解地图。
在creatures.py:
class Creature:
'''
Basic class for mobile active things like player and monsters
'''
from terrain import terrain
# ... some more code ...
def move(self, dx, dy):
'''
move creature by dx and|or dy
'''
if terrain.item(self.x+dx, self.y+dy).passable==True:
self.x+=dx
self.y+=dy
现在terrain 未在move 中定义并抛出NameError。当然,也可以是:
def move(self, dx, dy):
'''
move creature by dx and|or dy
'''
from terrain import terrain
self.x+=dx
self.y+=dy
它可以工作,但这样我必须在每个函数中导入它。这有点难看,那么正确的方法是什么?
【问题讨论】:
-
所有导入都应该在脚本的顶部,而不是在类/函数中。见the style guide。
标签: python namespaces