我正在尝试为国际象棋游戏创建一个Pawn类,但是我收到了错误" NameError:name' self'没有定义"在" can_move"函数的第一个if语句,即使我将颜色定义为初始化函数中的输入?有什么想法吗?
class Pawn(object):
def __init__(self, x, y, colour):
#store the pawns coords
self.x = x
self.y = y
#store the colour of the piece
self.colour = colour
#store if it moved yet or not
self.moved = False
self.print_value = self.colour+"P"
def can_move(newx, newy):
#func to check if piece can move along those coords
if self.colour == "W":
pieces = game_tracker.live_white
elif self.colour == "B":
pieces = game_tracker.live_black
答案 0 :(得分:2)
实例方法需要self
作为第一个参数
def can_move(self, newx, newy):
否则该方法不知道它在哪个实例上运行
答案 1 :(得分:1)
您需要添加self作为参数,表示类的当前实例。也缩进。
class Pawn(object):
def __init__(self, x, y, colour):
#store the pawns coords
self.x = x
self.y = y
#store the colour of the piece
self.colour = colour
#store if it moved yet or not
self.moved = False
self.print_value = self.colour+"P"
def can_move(self, newx, newy):
#func to check if piece can move along those coords
if self.colour == "W":
pieces = game_tracker.live_white
elif self.colour == "B":
pieces = game_tracker.live_black