我对 python 对象有一个问题,我在其中同时创建和迭代许多对象。
对象总是使用正确的属性创建的,但是当我遍历这些对象时,我会检查对象中的某个属性,这个特定属性会随机从对象中删除,然后我得到一个错误,即对象没有这个属性.
代码:
dead_list = []
for key, trackable_vehicle in self.lane_vehciles.items():
if trackable_vehicle.vehicle_status == 'DEAD' :
dead_list.append(key)
for key in dead_list:
save_object(trackable_vehicle.vehicle_type+'_'+str(trackable_vehicle.object_ID), trackable_vehicle)
self.lane_vehciles.pop(key, None)
错误:“TrackableTruck”对象没有属性“vehicle_status”
请注意,这段代码在 95% 的情况下都适用于我,尽管所有对象都具有相同的结构,但随机对象会发生这种情况。
经过大量调试后,我无法理解为什么会发生这种情况。该对象已正确创建,如果我在迭代之前打印它确实具有“vehicle_status”属性但在迭代后该属性从对象中消失
例如:
创建时的对象:{“object_ID”:55,“vehicle_type”:“truck”,“OTS”:“2020-03-10 16:07:16”,“lane_ID”:2.0,“vehicle_status”:“ALIVE”}
迭代后的对象:{“object_ID”:55,“vehicle_type”:“卡车”,“OTS”:“2020-03-10 16:07:16”,“lane_ID”:2.0}
我希望比我更了解python的人可以帮助我。谢谢
编辑对象定义:
class TrackableTruck:
def __init__(self, object_ID, vehicle_type, OTS, lane_ID, vehicle_status):
# info from tracking server
self.object_ID = object_ID
self.vehicle_type = vehicle_type
self.OTS = OTS
self.lane_ID = lane_ID
self.vehicle_status = vehicle_status
检查和更改车辆状态的代码:
d = pickle.loads(full_msg[self.HEADERSIZE:])
d = json.loads(d)
vehicle_type = str(d['vehicle_type'])
vehicle_lane = int(d['lane_ID'])
vehicle_id = int(d['object_ID'])
vehicle_status = d['vehicle_status']
if vehicle_lane == 1:
trackable_vehicle = self.streetLane_1.get_vehicle(vehicle_id)
if trackable_vehicle is None:
self.streetLane_1.add_vehicle(d)
else:
trackable_vehicle.vehicle_status = 'DEAD'
对象创建代码:
def object_decoder(self,json_obj):
return TrackableTruck(int(json_obj['object_ID']), json_obj['vehicle_type'], json_obj['OTS'], json_obj['lane_ID'], json_obj['vehicle_status'])
def add_vehicle(self, json_obj):
trackable_vehicle = self.object_decoder(json_obj)
self.lane_vehciles[int(trackable_vehicle.object_ID)] = trackable_vehicle