TypeError: 尝试从字典调用对象时 'list' 对象不可调用
我正在为学校的作业写一个国际象棋的程序,但遇到了一个我无法解决的问题。
def askpiece(self,player):
inputstring=input(player.name+ ", what is the location of the piece you would like to move (e.g.)? ")
x,y=inputstring
y=int(y)
if (x,y) in self and self[(x,y)].name[1] == player.tag:
if self[(x,y)].canmove(self,player):
return (x,y)
else:
print("the selected piece currently can't move, try again.")
elif self[(x,y)].name[1] != player.tag:
print("the piece you are trying to move belongs to the other player, try again.")
self.askpiece(player)
elif (x,y) not in self:
print("there is currently no piece on the specified location, try again.")
def canmove(self,board,player): #controls if the piece can move in atleast one way
#included the function canmove too in case that is what is causing the error
lettertonumber={"a":1,"b":2,"c":3,"d":4}
numbertoletter={1:"a",2:"b",3:"c",4:"d"}
for move in self.canmove:
if lettertonumber[self.x]+move[0] in [1,4] and self.y+move[1] in [1,5]:
if (lettertonumber[self.x]+move[0],self.y+move[1]) in board:
if self.name[1] != player.tag:
return True
else:
return True
return False
当我调用这个函数时,它会正确地询问我想移动的棋子的位置信息(比如说b1上的车),然后检查这个棋子是否存在,以及这个棋子是否属于我。但是接下来却出现了一个类型错误(TypeError):
File "Schaak.py", line 31, in <module>
game()
File "Schaak.py", line 27, in game
(x,y)=askpiece(bord,player)
File "Schaak.py", line 9, in askpiece
if board[(x,y)].canmove(board,player) == True:
TypeError: 'list' object is not callable
在askpiece这个函数里,self是一个叫“board”的字典,而self[(x,y)]是字典中的一个棋子。当我让代码打印self[(x,y)]时,它正确地显示这个对象是“类:车”。如果我让它打印这个对象本身,输出也没问题。无论我怎么改变语法,我似乎总是会遇到这个错误(除非我改成其他会产生不同错误的代码),而在代码的其他部分,当我调用self[(x,y)]时并没有出现任何错误。
2 个回答
0
在你的代码的某个地方,canmove
被赋值成了一个 list
(列表),所以当你尝试运行 canmove(board,player)
时,就会出现这个错误:
In [26]: canmove = []
In [27]: canmove = []
In [28]: canmove()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-28-2a6706ff3740> in <module>()
----> 1 canmove()
TypeError: 'list' object is not callable
1
在canmove()
这个函数里,这一行代码
for move in self.canmove:
意味着你在某个时候把这个属性设置成了一个列表。方法和实例变量是在同一个命名空间里的(实际上,方法就是一个可以被调用的[类]变量),所以你不能重复使用同样的名字。你必须改一个名字;因为这个列表变量看起来更可能只是内部使用,我建议把它改成_canmove
,除非有更合适的名字可以用。