I have a class named CAN_MSG for which I want to define the __eq__ method so that I can check two classes for equality.
Input_CAN_Sorter.py:
class CAN_MSG:
def __init__(self, first_sensor_id, timestamp, sensor_data):
self.first_sensor_id = first_sensor_id
self.sensor_data = sensor_data
self.timestamp = timestamp
def __eq__(self, other):
result = self.first_sensor_id == other.first_sensor_id
n = len(self.sensor_data) # no Error
i = len(other.senor_data) # AttributeError: 'CAN_MSG' object has no attribute 'senor_data'.
result = result and len(self.sensor_data) == len(other.senor_data)
for i in range(len(self.sensor_data)):
result = result and self.sensor_data[i] == other.senor_data[i]
result = result and self.timestamp == other.timestamp
return result
The class has a list of ints called sensor_data. When I compare using __eq__(self, other):
There is no problem with len(self.sensor_data), but with len(other.sensor_data) I get the following error:
AttributeError: 'CAN_MSG' object has no attribute 'senor_data'.
I don't understand why I can access self.sensor_data but not other.sensor_data.
test.py:
from Input_CAN_Sorter import CAN_MSG
list_temp = [1, 2, 3, 4, 5, 6, 7]
list_temp2 = [1, 2, 3, 4, 5, 6, 7]
CAN_MSG_1 = CAN_MSG(1, "TIME", list_temp)
CAN_MSG_2 = CAN_MSG(1, "TIME", list_temp2)
if CAN_MSG_1 == CAN_MSG_2:
print("=")
In C I would have done a check for the class type before and maybe a cast afterwards so that the compiler knows for sure that it is the same class, but in Python this is not possible/necessary if I understand correctly.
Probably this is a completely stupid mistake but I'm not 100% familiar with Python and can't come up with a reasonable explanation.
CodePudding user response:
You misspelled your variable name.
AttributeError: 'CAN_MSG' object has no attribute 'senor_data'.
i = len(other.senor_data)
You meant to write:
i = len(other.sensor_data)
