python对象中的实例化失败

python对象中的实例化失败,python,class,instance,Python,Class,Instance,我的第一次python体验有点问题。我在做一个小游戏,比如迷宫。我创建了一个类Map,当我实例化它时,它就可以工作了。当我尝试将同一个类实例化两次时,我遇到了一些问题 代码如下: from random import randint class Map: """Class that generates map""" width = 0 height = 0 map = list() dictLine = dict() def __init__(s

我的第一次python体验有点问题。我在做一个小游戏,比如迷宫。我创建了一个类
Map
,当我实例化它时,它就可以工作了。当我尝试将同一个类实例化两次时,我遇到了一些问题

代码如下:

from random import randint
class Map:
    """Class that generates map"""
    width = 0
    height = 0
    map = list()
    dictLine = dict()

    def __init__(self, width, height):
        """Constructor takes width and height in input"""
        self.width = width
        self.height = height
        for i in range(0, self.width * self.height):
            self.map.append('.')
        self.__defineMap()
        self.__defineEntrance()

    def __defineMap(self):
        """Defines Map in a dict"""
        index = 0
        for i in range(0,self.height):
            self.dictLine[index] = self.map[index:index + self.width]
            index = index + self.width

    def printMap(self):
        """Function that prints Wumpus World Map"""
        for i in range(0, self.width * self.height):
            if(i % self.width == 0):
                print()
            print(self.map[i], end='   ')
        print()

    def __defineEntrance(self):
        """Random entrance defined at game start"""
        state = False
        while state is False:
            randomEntrance = randint(0,(self.width * self.height)-1)
            self.map[-self.width:]
            if randomEntrance in range(0,self.width):
                #if entrance is at the first line
                self.map[randomEntrance] = 'E'
                return True
            elif randomEntrance % self.width == 0:
                #if entrance is on the left side
                self.map[randomEntrance] = 'E'
                return True
            for key in self.dictLine.keys():
                #da vedere
                if key + self.width - 1 == randomEntrance:
                    self.map[randomEntrance] = 'E'
                    return True
            l = list()
            for key in self.dictLine.keys():
                l.append(key)
            l.sort()
            l.reverse()
            if randomEntrance in range(l[0], l[0] + self.width):
                self.map[randomEntrance] = 'E'
                return True
        return False

    def reset(self):
        self.__init__(self.width, self.height)
结果是:

>>> map = Map(6,6)
>>> map.printMap()

.   .   .   E   .   .   
.   .   .   .   .   .   
.   .   .   .   .   .   
.   .   .   .   .   .   
.   .   .   .   .   .   
.   .   .   .   .   .  

>>> map2 = Map(7,7)
>>> map2.printMap()

.   .   .   E   .   .   .   
.   .   .   .   .   .   .   
.   .   .   .   .   .   .   
.   .   .   .   .   .   .   
.   .   .   .   .   .   .   
.   .   .   .   .   .   .   
.   .   .   E   .   .   .  

我怎样才能解决这个问题?谢谢大家!

map
是类属性(在类的所有实例之间共享),而不是实例属性


如果这不是您想要的行为,请将其更改为实例属性——也就是说,将
map=list()
部分移动到
\uuuu init\uuu
内部。您可能也希望对
宽度
高度
听写线
做同样的事情,首先要做的事情

如上所述,所有变量都创建为class属性,而不是instance,因此您在一个实例中所做的任何更改都将影响其他实例(甚至您将创建的那些)。解决方案是将它们移动到
\uuuu init\uuuu

此外,尽量不要使用“保留”字<代码>地图是一个内置的。也许把它改成迷宫

我对你的代码做了一些快速更改。有一些改进的空间,但它将很好地为您服务:

from random import randint


class Maze(object):
    """Class that generates maze"""

    def __init__(self, columns, rows):
        """Constructor takes columns and rows in input"""
        self.columns = columns
        self.rows = rows
        self.reset()

    def reset(self):
        # Building maze.
        self.__maze_cell_mapping = []
        for i in xrange(self.columns):
            for j in xrange(self.rows):
                self.__maze_cell_mapping.append((i, j))

        # Defining entrance.
        self.__entrance = None
        self.__define_entrance()

    def __define_entrance(self):
        """Random entrance defined at game start"""
        while self.__entrance is None:
            cell_id = randint(0, len(self.__maze_cell_mapping))
            if self.__is_boundary(cell_id):
                self.__entrance = self.__maze_cell_mapping[cell_id]

    def __is_boundary(self, cell_id):
        """
        :param int cell_id:
            ID of the cell to check.

        :rtype: bool
        :returns:
            ``True`` if given ``cell_id`` is at maze boundary.
        """
        column, row = self.__maze_cell_mapping[cell_id]
        if column == 0 or column == self.columns - 1:
            return True
        elif row == 0 or row == self.rows - 1:
            return True
        else:
            return False

    def print_maze(self):
        """Function that prints Wumpus World Maze"""
        result = [
            ['.'] * self.columns
            for _i in xrange(self.rows)
        ]

        column, row = self.__entrance
        result[column][row] = 'E'

        for row in result:
            print('   '.join(row))

希望有帮助

请记住,调用类实例
map
将覆盖内置的
map()
函数谢谢您的回答。我试图在构造函数中移动map=list(),但出现了一个新问题:>>>来自map import*>>>mappa=map(5,5)回溯(最近一次调用):文件“”,第1行,在文件“/Users/Marco/Desktop/Wumpus World/map.py”中,第16行,在init self.map.append('.')中AttributeError:“Map”对象没有属性“Map”。您的回溯表明,在声明它之前,您正试图将内容附加到
self.Map
(请认真阅读错误消息)。确保定义位于
\uuu init\uu
的最顶端。