【问题标题】:Class Help: "NameError: name 'self' is not defined"类帮助:“NameError:未定义名称‘self’”
【发布时间】:2015-03-12 21:51:08
【问题描述】:

我正在尝试为国际象棋游戏创建 Pawn 类,但在“can_move”函数的第一个 if 语句中出现错误“NameError: name 'self' is not defined”,即使我将颜色定义为在初始化函数中输入?有什么想法吗?

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

【问题讨论】:

  • 将自己传递给 can_move。

标签: python class


【解决方案1】:

实例方法需要self作为第一个参数

def can_move(self, newx, newy):

否则该方法不知道它在哪个实例上运行

【讨论】:

    【解决方案2】:

    您需要添加 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
    

    【讨论】:

    • 啊,看来我做错了,应该注意自我! (也正确缩进只是将其粘贴错误)。感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2017-11-20
    • 2014-01-25
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多