简体   繁体   中英

Class Help: “NameError: name 'self' is not defined”

I am attempting to create a Pawn class for a chess game, but I get the error "NameError: name 'self' is not defined" in the "can_move" function's first if statement, even though I define the colour as the input in the initialise function? Any ideas?

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

Instance methods need self as first argument

def can_move(self, newx, newy):

Otherwise the method does not know which instance it is operating on

You need to add self as an argument, representing the current instance of the class. Also indent.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM