Python TypeError问题:get_manhattan_distance()需2参数却传入3个
问题描述
用户编写了计算角色位置到最近食物曼哈顿距离的代码,其中state结构为((x, y), ("some status")),food_coords是网格坐标列表[(x, y), ...]。调用get_manhattan_distance(pos, food_pos)时触发错误:
TypeError: GridProblem.get_manhattan_distance() takes 2 positional arguments but 3 were given
注:调用时角色位置与食物处于同一网格位置。相关代码:
# helper function to calculate the manhattan distance def get_manhattan_distance(p, q): distance = 0 for p_i,q_i in zip(p,q): distance += abs(p_i - q_i) return distance # heuristic = Manhattan distance def h(self, node): if self.is_goal(node.state): return 0 pos = node.state[0] #current position (x, y) x_coord = node.state[0][0] y_coord = node.state[0][1] distances = [] for food_pos in self.food_coords: print('pos=',pos) print('food_pos=',pos) distances.append(self.get_manhattan_distance(pos, food_pos)) distances.sort() return distances[0]
错误原因与解决方案
核心错误原因
get_manhattan_distance是普通全局函数,但在h方法中用self.get_manhattan_distance(pos, food_pos)调用时,会自动把self作为第一个参数传入,导致实际传递了3个参数(self、pos、food_pos),但函数定义只接受2个参数(p、q),触发参数不匹配错误。
此外代码还有一处打印错误:print('food_pos=',pos)应该输出food_pos变量,而非pos。
两种修复方案
方案1:将全局函数改为类方法
给get_manhattan_distance添加self参数,使其成为类的成员方法:
# 修改为类方法,添加self参数 def get_manhattan_distance(self, p, q): distance = 0 for p_i,q_i in zip(p,q): distance += abs(p_i - q_i) return distance # heuristic = Manhattan distance def h(self, node): if self.is_goal(node.state): return 0 pos = node.state[0] #current position (x, y) distances = [] for food_pos in self.food_coords: print('pos=',pos) print('food_pos=',food_pos) # 修复打印错误 distances.append(self.get_manhattan_distance(pos, food_pos)) distances.sort() return distances[0]
方案2:直接调用全局函数
去掉调用时的self.前缀,直接使用函数名调用:
# helper function to calculate the manhattan distance def get_manhattan_distance(p, q): distance = 0 for p_i,q_i in zip(p,q): distance += abs(p_i - q_i) return distance # heuristic = Manhattan distance def h(self, node): if self.is_goal(node.state): return 0 pos = node.state[0] #current position (x, y) distances = [] for food_pos in self.food_coords: print('pos=',pos) print('food_pos=',food_pos) # 修复打印错误 distances.append(get_manhattan_distance(pos, food_pos)) # 去掉self. distances.sort() return distances[0]
额外优化建议
- 可以用
min()直接获取最小距离,省去排序后取第一个的步骤,简化代码:return min(get_manhattan_distance(pos, fp) for fp in self.food_coords) - 代码中
x_coord和y_coord变量未使用,可以删除。
内容的提问来源于stack exchange,提问作者Moe
相关产品推荐
相关产品推荐

