python 重载了比较运算符为什么!=也能用_Python重载比较运算符

对象包含的内置方法

class MyObj(object):

def __init__(self):

self.value = 0

myObj = MyObj()

print(dir(myObj))

返回结果

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'value']

其中和对象比较的内置方法包括:

['__eq__', '__ge__', '__gt__', '__le__', '__lt__', '__ne__']

_convert = {

'__lt__': [('__gt__', _gt_from_lt),

('__le__', _le_from_lt),

('__ge__', _ge_from_lt)],

'__le__': [('__ge__', _ge_from_le),

('__lt__', _lt_from_le),

('__gt__', _gt_from_le)],

'__gt__': [('__lt__', _lt_from_gt),

('__ge__', _ge_from_gt),

('__le__', _le_from_gt)],

'__ge__': [('__le__', _le_from_ge),

('__gt__', _gt_from_ge),

('__lt__', _lt_from_ge)]

}

def total_ordering(cls):

"""Class decorator that fills in missing ordering methods"""

# Find user-defined comparisons (not those inherited from object).

roots = [op for op in _convert if getattr(cls, op, None) is not getattr(object, op, None)]

if not roots:

raise ValueError('must define at least one ordering operation: < > <= >=')

root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__

for opname, opfunc in _convert[root]:

if opname not in roots:

opfunc.__name__ = opname

setattr(cls, opname, opfunc)

return cls

这样一来,只要你在定义class的时候加上这个注解,再重写运算符的时候,除了 __eq__和__ne__之外,其他的4个只需要重写一个就可以了,@functools.total_ordering直接就帮你完成了其他比较方法的重写。

@functools.total_ordering

class MyObj(object):

def __init__(self):

self.value = 0

def __eq__(self, other):

self

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值