从字典中将类对象作为对象调用

时间:2019-05-31 01:28:55

标签: python

我有一个类对象的字典。我需要拉该对象以使其执行其功能之一。这些对象没有变量名,它们是由for循环创建的。

这是我尝试过的:

    class Pawn(object):
     def legal_moves(self):
         ...
         return moves_list

    ...
    # main
    dictionary = {'a2': <class '__main__.Pawn'>, 'b2': <class '__main__.Pawn'> etc.}

    pawn_obj = dictionary['a2']

    moves = pawn_obj.legal_moves()

完整版本的代码:

  class Pawn(Piece):
    def __init__(self, color):
        self.type = "P"
        super(Pawn, self).__init__(color, self.type)

    def legal_moves(self, position, map):
        self.l_moves = []
        file = int(position[:1])
        rank = int(position[1:])

        if self.color == "w" and rank == 2:
            move1 = str(rank + 1) + str(file)
            move2 = str(rank + 2) + str(file)
            self.l_moves.append(move1)
            self.l_moves.append(move2)
        return self.l_moves

#main
b = Board(white_view=True)

p = Pawn("w")

p = b.map.get("12")
print(type(p))

moves = p.legal_moves("12", b.map)
print(moves)

退货:

<class '__main__.Pawn'>

 File "C:/Users/" line 173, in <module>
  moves = p.legal_moves("12", b.map)

TypeError: 'list' object is not callable

Process finished with exit code 1```

1 个答案:

答案 0 :(得分:1)

我同意Barmar's comment

我会为self.legal_moves的项目进行CTRL-F查找其值设置为列表的位置。

您发布的其他代码显示Pawn具有列表的属性l_moves。也许在创建Pawn.legal_moves函数之前,该属性以Pawn.legal_moves()开头,而您却错过了重命名它的位置?

尝试添加以下调试行,以获取有关该情况中实际包含的内容的提示:

p = b.map.get("12")
print(type(p))

# new lines
print(type(p.legal_moves))  # if <class 'list'>, we're on the right track; if <class 'method'> we need to look elsewhere
print(p.legal_moves))  # if it's a list, its contents might give you a clue about where it's being set

moves = p.legal_moves("12", b.map)