函数返回的值不正确

2024-04-24 16:00:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码来构建一个数组ADT,但是我的__eq__()函数不起作用

class Array:

    def __init__(self, max_capacity):
        self.array = build_array(max_capacity)
        self.size = 0
        self.index = 0
        self.maxsize = max_capacity

    def __str__(self):
        string = "["
        for i in range(self.size):
            string += str(self.array[i])
            string += ', '
        string += ']'
        return string

    def __eq__(self, other):     
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        return False

if __name__ == "__main__":
    test_array = Array(6)

    test_array1 = Array(6)

    print(test_array.__eq__(test_array1))
    print(test_array)
    print(test_array1)

现在,test_array.__eq__(test_array1)正在返回False当它应该是明确的True时,我甚至打印出所有内容来确保。我不知道它为什么会返回False,任何帮助都将不胜感激。你知道吗

这是构建数组的函数代码

import ctypes


def build_array(size):
    if size <= 0:
        raise ValueError("Array size should be larger than 0.")
    if not isinstance(size,  int):
        raise ValueError("Array size should be an integer.")
    array = (size * ctypes.py_object)()
    array[:] = size * [None]
    return array

Tags: testselffalsesizestringreturnifdef
1条回答
网友
1楼 · 发布于 2024-04-24 16:00:45

您要求Python比较两个ctypes数组(所有其他键值对都是比较相等的对象)。你知道吗

ctypes数组只有在引用同一对象时才相等

>>> a = build_array(6)
>>> b = build_array(6)
>>> a == b
False
>>> a == a
True

如果它们具有相同的长度并且包含相同的元素,则不支持测试。您必须手动执行此操作:

def __eq__(self, other):     
    if not isinstance(other, type(self)):
        return False
    if (self.index != other.index or self.size != other.size or
            self.maxsize != other.maxsize):
        return False
    return all(a == b for a, b in zip(self.array, other.array))

相关问题 更多 >