我忘了我的基本python技能我做错了什么?
我很少忘记python,因为我很久没有使用它了,而且我无法解决这个看似非常基本的错误 我正在用一种非常简单的方法来编写一个国际象棋引擎,但我不能正确地分离类的实例 在我的代码中:我忘了我的基本python技能我做错了什么?,python,Python,我很少忘记python,因为我很久没有使用它了,而且我无法解决这个看似非常基本的错误 我正在用一种非常简单的方法来编写一个国际象棋引擎,但我不能正确地分离类的实例 在我的代码中: class Piece: def __init__(self, name='', symbol='', color='', value=0, position=(0,0)): self.name=name self.color=color ... class Army: def __init_
class Piece:
def __init__(self, name='', symbol='', color='', value=0, position=(0,0)):
self.name=name
self.color=color
...
class Army:
def __init__(self, color="", pieces=[]):
self.color=color
self.pieces=pieces
black=Army()
for rank in range(8):
black.pieces.append(Piece())
black.pieces[rank].color="B"
print(Army().pieces[rank].color)
输出:
B
B
B
B
B
B
B
B
而不是默认为“”的片段()。请注意,输出指向Army(),而不是预期输出的black实例
单独的类实例不应该采用单独的值吗?我真的搞不懂发生了什么事
我的全部代码是:
class Game:
def __init__(self, name="chess",score=0,board=""):
self.name=name
self.board=board
self.score=score
class Board:
def __init__(self, position="", size=[8,8]):
self.size=size
self.position=position
class Piece:
def __init__(self, name='', symbol='', color='', value=0, position=(0,0)):
# vector=[[0,0],[0,0]])
self.name=name
self.color=color
self.value=value
self.position=position
# self.vector=vector
class Army:
def __init__(self, color="", pieces=[]):
self.color=color
self.pieces=pieces
chess=Game()
chess.name="FIDE"
chess.board=Board()
chess.board.size=[8,8]
checker=Piece()
checker.name="checker"
checker.value=100
checker.vector=(1,0)
black=Army()
black.color="B"
for rank in range(8):
black.pieces.append(Piece())
black.pieces[rank].color="B"
print(Army().pieces)
white=Army()
white.color="W"
for rank in range(8):
white.pieces.append(Piece())
white.pieces[rank].color="W"
print( len(black.pieces))
for ch in white.pieces:
print (ch.color)
print(black)
print(white)
print(len(white.pieces))
print(black.color)
#print (white.pieces.color)
我想这是因为不应该使用可变列表作为默认值。
Board()
的所有实例都保留对相同大小的引用。所有的Army()
实例也使用相同的parties
列表
请尝试使用下面描述的方法更新代码:
def uuuu init_uuuuuu(self,color=”“,pieces=[]):
self.pieces=碎片
# ->
def uuu init uuuu(self,color=”“,pieces=None):
如果没有:
件数=[]
self.pieces=碎片
因此,您将为每个\uuuu init\uuuu()
调用创建一个新的、单独的列表实例
更多信息:请提供预期的(MRE)。显示中间结果与您预期的不同之处。我们应该能够复制和粘贴一个连续的代码块,执行该文件,并再现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和期望的输出来测试我们的建议。您的代码段不是独立的。你的整个计划太过分了。请关注问题,发布最少的代码,并包括您的值跟踪。请注意,“我忘记了我的Python技能”是一个挥动的“红旗”,表明堆栈溢出是解决此问题的错误站点。请从下一页重复和。堆栈溢出不是为了替换现有的文档和教程。这是否回答了您的问题?我试试看,但我不明白。你的意思是如果两个变量有相同的值,它们是相同的并且更新相同的吗?或者更准确地说,如果两个列表为空,它们更新的内容相同?奇怪,让我试试。圣人治疗法。解决了,谢谢!我的意思是,当您编写pythondeffn(lst=[]):代码>这实际上意味着python\u default\u lst=[]定义fn(lst=\u default\u lst):代码>调用函数时,它不会创建新列表,它使用已创建的列表(并绑定到其他军队),因此您需要在函数体中声明列表,而不是在其签名中声明列表。