【问题标题】:Testing a Key with cartesian coordinates in my dictionary在我的字典中使用笛卡尔坐标测试键
【发布时间】:2014-11-16 23:56:01
【问题描述】:
class Position:
    def __init__(self, x,y):
        self.x = int(x)
        self.y = int(y)
    def __eq__(self, other):

        return self.x == other.x and self.y == other.y

    def __repr__(self):
        return '({}, {})'.format(self.x, self.y)

    def __hash__(self):
        return hash(str(self))


class Piece:


    def __init__(self, color, type_piece):
        self.color = color
        self.type_piece = type_piece

    def is_pawn(self):

        return self.type_piece == "pawn"

    def is_queen(self):
        return self.type_piece == "queen"

    def is_white(self):
        return self.color == "white"

    def is_balck(self):
        return self.color == "black"

    def change(self):
        self.type_piece = "queen"

    def __repr__(self):
        if self.is_white() and self.is_pawn():
            return "o"
        elif self.is_white() and self.is_queen():
            return "O"
        elif self.is_black() and self.is_pawn():
            return "x"
        else:
            return "X"

class board:

    def __init__(self):
        self.n_x = 8
        self.n_y = 8

        self.cases = { Position(1,1):Piece("white","pawn") }  #example of what my dict contains

    def check_piece(self, position):

        if Position(position) in self.cases.keys():
            return cases.get(Position(position))
        else:
            return False

当我尝试 check_piece((1,1))

TypeError: init() 缺少 1 个必需的位置参数:'colonne'

当我尝试 check_piece(1,1)

TypeError: recuperer_piece_a_position() 接受 2 个位置参数,但给出了 3 个...

任何帮助将不胜感激,我无法更改字典的结构,因为它是预建的

【问题讨论】:

  • 似乎没有足够的关于你的类和对象的信息。此外,还有更简洁的结构,如cases.get(something, False)
  • 不幸的是,我可能不会发布所有课程,更不用说整个家庭作业了,目前我被这两个错误消息卡住了,我无法收回我的密钥的价值以继续......

标签: python-3.x


【解决方案1】:

check_piece 接受一个参数,而Position 接受两个参数。

试试类似的东西

def check_piece(position):

    return cases.get(Position(*position), False)

check_piece((1,1)) 也可以。

【讨论】:

  • 为什么位置前有星号(*)?
  • 它解包元组,以便每个元素都用作函数的一个参数。见docs.python.org/2/tutorial/…
  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 2017-10-16
  • 2017-11-27
相关资源
最近更新 更多