python方法_Python中的通用__eq __()方法
您可以使用如下結(jié)構(gòu)獲取Class的所有屬性:
from itertools import chain
@classmethod
def _properties(cls):
type_dict = dict(chain.from_iterable(typ.__dict__.items() for typ in reversed(cls.mro())))
return {k for k, v in type_dict.items() if 'property' in str(v)}
__eq__會(huì)變成這樣:
def __eq__(self, other):
properties = self._properties() & other._properties()
if other._properties() > properties and self._properties() > properties:
# types are not comparable
return False
try:
return all(getattr(self, prop) == getattr(other, prop) for prop in properties)
except AttributeError:
return False
使用反轉(zhuǎn)(cls.mro())的原因是這樣的事情也有效:
class Worker(Person):
@property
def wage(self):
return 0
p4 = Worker('Raymond', 'Salemi')
print(p4 == p3)
06003
總結(jié)
以上是生活随笔為你收集整理的python方法_Python中的通用__eq __()方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html表单居中_如何在IE低版本中兼容
- 下一篇: clob和blob是不是可以进行模糊查询