我正在尋找比較同一類的兩個實體,但只比較兩者都不是的專案None。
例如,
我將有一Bolt堂課,一個實體將有:
bolt1.locx = 1.0
bolt1.locy = 2.0
bolt1.locz = 3.0
bolt1.rpid = 1234
bolt1.nsid = [1,2,3,4]
bolt2.locx = 1.0
bolt2.locy = 2.0
bolt2.locz = 3.0
bolt2.rpid = None
bolt2.nsid = None
在這種情況下,我想將這些類比較為真。
我知道我可以使用__dict__每個類的來遍歷屬性,但我想知道這是否可能是一個串列理解。
uj5u.com熱心網友回復:
我會保持簡單:
class Bolt:
# ...
def __eq__(self, other):
if [self.locx, self.locy, self.locz] != [other.locx, other.locy, other.locz]:
return False
if self.rpid is not None && other.rpid is not None && self.rpid != other.rpid:
return False
if self.nsid is not None && other.nsid is not None && self.nsid != other.nsid:
return False
return True
uj5u.com熱心網友回復:
我沒有完全滿足相等性的要求,但我認為
attrgetterfromoperator可能對比較回圈中的實體很有用。這里是一個使用示例:
from operator import attrgetter
attrs = ('locx', 'locx', 'locz', 'rpid', 'nsid')
checks = []
for attr in attrs:
attr1 = attrgetter(attr)(bolt1)
attr2 = attrgetter(attr)(bolt2)
if attr1 is None and attr2 is None:
continue
checks.append(attr1 == attr2)
print(all(checks))
uj5u.com熱心網友回復:
這是一種更通用的方法,不需要對屬性比較進行硬編碼
class Bolt:
def __eq__(self, other):
# check if the objects have a different set of attributes
if self.__dict__.keys() != other.__dict__.keys():
return False
for attr, self_attr in self.__dict__.items():
other_attr = getattr(other, attr)
if (self_attr is None) or (other_attr is None):
continue
elif self_attr != other_attr:
return False
return True
bolt1 = Bolt()
bolt2 = Bolt()
bolt1.locx = 1.0
bolt1.locy = 2.0
bolt1.locz = 3.0
bolt1.rpid = 1234
bolt1.nsid = [1,2,3,4]
bolt2.locx = 1.0
bolt2.locy = 2.0
bolt2.locz = 3.0
bolt2.rpid = None
bolt2.nsid = None
輸出:
>>> bolt1.__dict__
{'locx': 1.0, 'locy': 2.0, 'locz': 3.0, 'rpid': 1234, 'nsid': [1, 2, 3, 4]}
>>> bolt2.__dict__
{'locx': 1.0, 'locy': 2.0, 'locz': 3.0, 'rpid': None, 'nsid': None}
>>> bolt1 == bolt2
True
>>> bolt2.rpid = 1
>>> bolt2.__dict__
{'locx': 1.0, 'locy': 2.0, 'locz': 3.0, 'rpid': 1, 'nsid': None}
>>> bolt1 == bolt2
False # different 'rpid' attribute values
>>> bolt2.rpid = None
>>> bolt2.extra_attr = 2
>>> bolt2.__dict__
{'locx': 1.0, 'locy': 2.0, 'locz': 3.0, 'rpid': None, 'nsid': None, 'extra_attr': 2}
>>> bolt1 == bolt2
False # different set of attributes
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475779.html
上一篇:python-如何計算Python串列中具有特定值的字典項?
下一篇:從json檔案加載專案描述
