如何比较两个ctypes对象的相等性?

5
import ctypes as ct

class Point(ct.Structure):
    _fields_ = [
        ('x', ct.c_int),
        ('y', ct.c_int),
    ]

p1 = Point(10, 10)
p2 = Point(10, 10)

print p1 == p2 # => False

在上述简单示例中,等式运算符“==”的结果为False。有没有任何简单的方法?
编辑:以下是稍微改进过的版本(基于接受的答案),它也可以处理嵌套数组:
import ctypes as ct

class CtStruct(ct.Structure):

    def __eq__(self, other):
        for field in self._fields_:
            attr_name = field[0]
            a, b = getattr(self, attr_name), getattr(other, attr_name)
            is_array = isinstance(a, ct.Array)
            if is_array and a[:] != b[:] or not is_array and a != b:
                return False
        return True

    def __ne__(self, other):
        for field in self._fields_:
            attr_name = field[0]
            a, b = getattr(self, attr_name), getattr(other, attr_name)
            is_array = isinstance(a, ct.Array)
            if is_array and a[:] != b[:] or not is_array and a != b:
                return True
        return False

class Point(CtStruct):
    _fields_ = [
        ('x', ct.c_int),
        ('y', ct.c_int),
        ('arr', ct.c_int * 2),
    ]

p1 = Point(10, 20, (30, 40))
p2 = Point(10, 20, (30, 40))

print p1 == p2 # True
2个回答

9
创建一个名为MyCtStructure的类,那么它的所有子类都不需要实现__eq__和__ne__方法。在您的情况下定义eq将不再是一项繁琐的工作。
import ctypes as ct
class MyCtStructure(ct.Structure):

    def __eq__(self, other):
        for fld in self._fields_:
            if getattr(self, fld[0]) != getattr(other, fld[0]):
                return False
        return True

    def __ne__(self, other):
        for fld in self._fields_:
            if getattr(self, fld[0]) != getattr(other, fld[0]):
                return True
        return False

class Point(MyCtStructure):
    _fields_ = [
        ('x', ct.c_int),
        ('y', ct.c_int),
    ]


p1 = Point(10, 11)
p2 = Point(10, 11)

print p1 == p2

是的,那就可以了。对于嵌套结构非常好用。谢谢! - FipS

3

p1.x == p2.x and p1.y == p2.y 在这个简单的情况下可以正常工作。

您还可以在Point类中实现__eq__()__ne__()方法:

class Point(ct.Structure):
    _fields_ = [
        ('x', ct.c_int),
        ('y', ct.c_int),
    ]
    def __eq__(self, other):
        return (self.x == other.x) and (self.y == other.y)
    def __ne__(self, other):
        return not self.__eq__(other)

>>> p1 = Point(10, 10)
>>> p2 = Point(10, 10)
>>> p3 = Point(10, 66)
>>> p1 == p2
True
>>> p1 != p2
False
>>> p1 == p3
False
>>> p1 != p3
True

谢谢,这肯定是一个正确的方法。我忘了提到我正在寻找一种适用于复杂嵌套结构的简单方法。在我的情况下定义__eq__会有点繁琐... - FipS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接