gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:32 25 4
gpt4 key购买 nike

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

#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] 的对象的值变量

它看起来像:

 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

最佳答案

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

#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)]

关于Python:将对象存储在二维数组中并调用其方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com