Python:将对象存储在2d数组中并调用其方法

时间:2016-11-07 20:38:54

标签: python

我正在尝试制作国际象棋应用程序。代码如下:

#file containing pieces classes
class Piece(object):`

     name = "piece"
     value = 0
     grid_name = "____"


class Pawn(Piece):

# Rules for pawns.
#If first move, then can move forward two spaces

name = "Pawn"
value = 1
grid_name = "_PN_"
first_move = True


#Main file
from Piece import *



class GameBoard:

   pieces = []
   grid = [][]

   def __init__(self):

      self.grid[1][0] = self.pieces.append(Pawn())



currentBoard = GameBoard()

我想为位于grid [1] [0]

的对象调用value变量

看起来像是:

 print currentBoard.grid[1][0].value

这段代码没有用,它告诉我,我遗漏了有关对象和变量范围的内容。这是否可以在Python中使用?

编辑 - 解决方案

我确实找到了一个解决方案,使用网格列表来保存对片段列表中对象的索引的引用。代码如下:

class GameBoard:

    # initialize empty board
    grid = [["____" for i in range(8)] for j in range(8)]
    pieces = []

    def __init__(self):

        self.grid[0][0] = 0
        self.grid[0][1] = 1
        self.grid[0][2] = 2
        self.grid[0][3] = 3
        self.grid[0][4] = 4
        self.grid[0][5] = 5
        self.grid[0][6] = 6
        self.grid[0][7] = 7
        self.grid[1][0] = 8
        self.grid[1][1] = 9
        self.grid[1][2] = 10
        self.grid[1][3] = 11
        self.grid[1][4] = 12
        self.grid[1][5] = 13
        self.grid[1][6] = 14
        self.grid[1][7] = 15


pieces = []

pieces.append(Pawn())

#grid will return the integer which can be passed to the other list to pull an 
#object for using the .value attribute

print pieces[currentBoard.grid[1][0]].value

1 个答案:

答案 0 :(得分:1)

重写代码,使其只作为单个文件运行:

#file containing pieces classes
class Piece(object):
     name = "piece"
     value = 0
     grid_name = "____"


class Pawn(Piece):
    # Rules for pawns.
    #If first move, then can move forward two spaces

    name = "Pawn"
    value = 1
    grid_name = "_PN_"
    first_move = True

class GameBoard:

   pieces = []
   grid = [[],[]]

   def __init__(self):

      self.grid[0][1] = self.pieces.append(Pawn())



currentBoard = GameBoard()

有一些事情需要纠正。例如,PiecePawnGameBoard中定义的变量未在__init__()方法下定义。这意味着这些变量将由该类的所有实例共享。

示例:

>>> pawn1 = Pawn()  # Make two Pawns
>>> pawn2 = Pawn()
>>> print pawn1.first_move, pawn2.first_move
True, True
>>> pawn1.first_move = False  # Change the first pawns attribute
>>> print pawn1.first_move, pawn2.first_move # But both change
False, False

要避免这种情况,请在方法__init__()下为所有三个类定义类属性。

示例:

class Pawn(Piece):
    # Rules for pawns.
    #If first move, then can move forward two spaces
    def __init__(self):
        self.name = "Pawn"
        self.value = 1
        self.grid_name = "_PN_"
        self.first_move = True

接下来,您的变量grid未在python中正确定义。如果您想要一个包含两个空列表的列表,您可以执行以下操作

grid = [[], []]

但制作8x8空列表结构的简单方法是执行以下操作

grid = [[[] for i in xrange(8)] for j in xrange(8)]