python存储对象的数组_Python:在2d数组中存储对象并调用其方法
我正在嘗試制作一個象棋應用程序。代碼如下:#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變量
它看起來像:
^{pr2}$
這段代碼不起作用,這說明我缺少一些關于對象和變量范圍的信息。這在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
總結
以上是生活随笔為你收集整理的python存储对象的数组_Python:在2d数组中存储对象并调用其方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小程序和vue语法对比_React语法开
- 下一篇: 怎样保存python源程序_五分钟教会你