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
クラス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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加