Python向列表追加Point类变量时旧值被覆盖的问题排查
问题排查与解决方案
问题根源
Python中对象采用引用传递,你在循环外仅创建了一个curr_odom = Point()对象,每次循环只是修改该对象的属性值后追加到odom_record列表中。实际上列表里的所有元素都是指向同一个curr_odom对象的引用,当你更新新的里程计数据时,列表中之前所有元素的属性都会同步变化,导致odom_record[-1]和odom_record[-2]指向同一个对象、值完全相同,计算出的距离差始终为0。
修复代码
核心修改是每次循环创建新的Point对象,避免复用同一个对象引用:
def execute_callback(self, goal_handle): self.get_logger().info('Executing goal...') feedback_msg = OdomRecord.Feedback() feedback_msg.current_total = 0.0 # 移除循环外的curr_odom定义,改为在循环内创建新对象 # curr_odom = Point() self.odom_record = [] self.last_x = 0.0 self.last_y = 0.0 self.second_last_x = 0.0 self.second_last_y = 0.0 self.total_distance = 0.0 # 为初始值创建独立的Point对象,避免后续被意外修改 self.first_odom = Point() self.first_odom.x = self.last_odom.x self.first_odom.y = self.last_odom.y self.odom_record.append(self.first_odom) iter = 0 while True: iter += 1 # 每次循环创建新的Point对象,存储当前里程计数据 curr_odom = Point() curr_odom.x = self.last_odom.x curr_odom.y = self.last_odom.y curr_odom.z = self.last_odom.z self.odom_record.append(curr_odom) # 后续逻辑保持不变 self.last_x = self.odom_record[-1].x self.last_y = self.odom_record[-1].y self.second_last_x = self.odom_record[-2].x self.second_last_y = self.odom_record[-2].y # DEBUGGING CODE...(省略原调试代码) self.total_distance = self.total_distance + self.dist_diff([self.last_x, self.last_y], [self.second_last_x, self.second_last_y]) self.get_logger().warn(f"TOTAL DISTANCE= {self.total_distance}") feedback_msg.current_total = self.total_distance goal_handle.publish_feedback(feedback_msg) self.first_last_dist = self.dist_diff([self.last_odom.x, self.last_odom.y], [self.first_odom.x, self.first_odom.y]) self.get_logger().info(f"DISTANCE TO INITIAL POSITION= {self.first_last_dist}") if self.first_last_dist < 0.05 and iter > 5: self.get_logger().warn("INITIAL POSITION REACHED!") break time.sleep(1.0)
验证逻辑
修改后,每次追加到odom_record的都是独立的Point对象,各自保存当前时刻的里程计数据,后续修改新对象不会影响之前的元素。此时计算列表最后两个元素的距离差会得到真实的移动距离,total_distance将正常累加。
内容的提问来源于stack exchange,提问作者Elie
相关产品推荐
相关产品推荐

