将对象导入 class

Importing an object to a class

如何将对象导入 class 的命名空间并使其可用于每个函数?假设我在 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

它可以工作,但那样我就必须在每个函数中导​​入它。这有点丑陋,那么正确的方法是什么?

如果所有的导入都在脚本的顶部会更好,但是如果你非常想这样做...

class SomeClass:
    def __init__(self):
        from Smith import John
        self.imp=John
    def run(self, args):
        self.imp.dosmth()