我的__eq __()函数没有返回正确的值

时间:2017-09-11 13:14:49

标签: python python-3.x ctypes

我有以下代码来构建数组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,任何帮助都会受到赞赏。

这是build_array函数代码

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

1 个答案:

答案 0 :(得分:2)

您要求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))