[英]I forgot my basic python skills What am I doing wrong?
我幾乎忘記了 python sdince 我有一段時間沒有使用它,我無法解決這個看似非常基本的錯誤。
我正在使用一種非常天真的方法來編寫國際象棋引擎,但我無法正確分離類的實例。
在我的代碼中:
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)
Output:
B
B
B
B
B
B
B
B
而不是 Piece() 默認的 '' 。 請注意,output 指向 Army() 而不是黑色實例,而 output 將是預期的。
單獨的 class 實例不應該采用單獨的值嗎? 我真的不知道發生了什么事。
我的完整代碼是:
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()
的所有實例都保持對相同size
列表的引用。 所有Army()
實例也使用相同的pieces
列表。
請嘗試使用以下描述的方法更新您的代碼:
def __init__(self, color="", pieces=[]):
self.pieces = pieces
# ->
def __init__(self, color="", pieces=None):
if pieces is None:
pieces = []
self.pieces = pieces
因此,您將為每個__init__()
調用創建一個新的、單獨的列表實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.