Python基础-面向对象(方法)
5 比较操作
作用
可以自定义对象 "比较大小, 相等以及真假" 规则
步骤
实现6个方法
相等
__eq__
不相等
__ne__
小于
__lt__
小于或等于
__le__
大于
__gt__
大于或等于
__ge__
注意
如果对于反向操作的比较符, 只定义了其中一个方法
但使用的是另外一种比较运算
那么, 解释器会采用调换参数的方式进行调用该方法
例如
定义了 "小于" 操作
x < y
使用 x > y
会被调换参数, 调用上面的 "小于操作"
但是, 不支持叠加操作
例如
定义了 "小于" 和 "等于" 操作
不能使用 x <= y
补充
使用装饰器, 自动生成"反向" "组合"的方法
步骤
1. 使用装饰器装饰类
@functools.total_ordering
2. 实现
> 或 >= 或 < 或 <= 其中一个
实现 ==
上下文环境中的布尔值
__bool__
class Person:
def __init__(self, age, height):
self.age = age
self.height = height
# == != > >= < <=
# 不一定需要全部实现,可方法是可以进行反向推到的
def __eq__(self, other):
print("eq")
return self.age == other.age
# def __ne__(self, other):
# pass
# def __gt__(self, other):
pass
# def __ge__(self, other):
# pass
def __lt__(self, other):
# print("lt")
print(self.age)
print(other.age)
return self.age < other.age
# def __le__(self, other):
# pass
p1 = Person(18, 190)
p2 = Person(19, 190)
print(p1 < p2)
# 当只实现 le 方法时,执行 le 反向操作是可行的,但是会将参数换位
print(p1 > p2) # p2 < p1
# 可以执行反向操作
print(p1 != p2)
import functools
@functools.total_ordering
class Person:
def __lt__(self, other):
print("lt")
# pass
return False
def __eq__(self, other):
print("eq")
pass
# def __le__(self, other):
# print("le")
p1 = Person()
p2 = Person()
print(p1 <= p2)
print(Person.__dict__)
>>> 打印结果
lt
eq
None
# 手动进行换行
{
'__eq__': <function Person.__eq__ at 0x10a5deb70>,
'__lt__': <function Person.__lt__ at 0x10a5debf8>,
'__gt__': <function _gt_from_lt at 0x10a57ef28>,
'__le__': <function _le_from_lt at 0x10a581048>,
'__ge__': <function _ge_from_lt at 0x10a5810d0>
'__module__': '__main__',
'__doc__': None,
'__hash__': None,
'__dict__': <attribute '__dict__' of 'Person' objects>,
'__weakref__': <attribute '__weakref__' of 'Person' objects>,
}
- 上下文环境中的布尔值
__bool__
,用于控制实例对象的布尔值
# 通常是非空即真
class Person:
pass
p = Person()
if p: #能够被执行
print("xx")
# 通过 __bool__ 来控制 p 实例的布尔值
class Person:
def __init__(self):
self.age = 20
def __bool__(self):
return self.age >= 18
pass
p = Person()
if p:
print("xx")
网友评论