【问题标题】:Importing an object to a class将对象导入类
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2018-07-21
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多