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

2024-09-28 20:44:48 发布

您现在位置: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```

Tags: 对象selfmapmaindeftypepositionclass
1条回答
网友
1楼 · 发布于 2024-09-28 20:44:48

我同意Barmar's comment。你知道吗

我将在项目中按CTRL-F键self.legal_moves查找其值设置为列表的位置。你知道吗

您发布的其他代码显示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)

相关问题 更多 >