Python: __eq__(self, other): len(self.sensor_data) 好的,但是 len(other.senor_data) => AttributeError

Python: __eq__(self, other): len(self.sensor_data) ok, but len(other.senor_data) => AttributeError

我有一个名为 CAN_MSG 的 class,我想为其定义 __eq__ 方法,以便我可以检查两个 class 是否相等。

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

class 有一个名为 sensor_data 的整数列表。当我使用 __eq__(self, other): 进行比较时 len(self.sensor_data) 没有问题,但是 len(other.sensor_data) 我得到以下错误:

AttributeError: 'CAN_MSG' 对象没有属性 'senor_data'。

我不明白为什么我可以访问 self.sensor_data 而不能访问 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("=")

在 C++ 中,我会在之前对 class 类型进行检查,然后可能会进行强制转换,以便编译器确定它是相同的 class,但在 [=45] =] 这不是 possible/necessary 如果我没理解错的话。

可能这是一个完全愚蠢的错误,但我不是 100% 熟悉 Python 并且无法提出合理的解释。

你拼错了变量名。

AttributeError: 'CAN_MSG' object has no attribute 'senor_data'.

i = len(other.senor_data)

您打算写:

i = len(other.sensor_data)