
我们在python中经常要自定义类,可能要进一步实现类的一些运算
1.定义Point类class Point():
def __init__(self,x,y,z,name):
self.x=x
self.y=y
self.z=z
self.name=name
2.实例化2个Point对象p1,p2,尝试比较p1,p2
p1=Point(1,1,2,'p1')
p2=Point(2,2,3,'p2')
print(p1<p2)
# Traceback (most recent call last):
# File "test.py", line 37, in
# print(p1
# TypeError: '<' not supported between instances of 'Point' and 'Point'
发现’<'不支持Point对象
由于Point类是我们自己定义的,'<'的比较行为必须需要我们自己设定,到底是比较x坐标还是y坐标,还是name?还是都比较?
3.在Point类代码中添加__lt__定义’<'的具体比较方式 def __lt__(self,other): # 只比较x坐标,当然也可以换成y或者z
print('<<<<<<<<<<<<<<<')
return self.x<other.x
重新测试结果
print(p1<p2)
# <<<<<<<<<<<<<<<
# True
4.修改__lt__
先比较x,如果x相等,再比较y;如果y相等,再比较z;如果z也相等,再比较name
def __lt__(self,other):
print('<<<<<<<<<<<<<<')
return (self.x,self.y,self.z,self.name)<(other.x,other.y,other.z,other.name)
实例化p3,p4,进行比较
p3=Point(1,4,5,'p3')
p4=Point(3,4,2,'p4')
print(p3<p4)
# <<<<<<<<<<<<<<
# True
这里其实就是按照x,y,z,name的顺序依次比较过去,遇到第一个不相等,判断结果后输出,后面不在比较
如果遇到2个x,y,z,name完全一样的Point
p5=Point(1,2,3,'p5')
p5_2=Point(1,2,3,'p5')
print(p5<p5_2)
# <<<<<<<<<<<<<<
# False
5.虽然我们定义了__lt__,但是__lt__不能实现<=的功能
print(p3<=p4)
# Traceback (most recent call last):
# File "test.py", line 53, in
# print(p3<=p4)
# TypeError: '<=' not supported between instances of 'Point' and 'Point'
必须进一步定于<=,也就是__le__
def __le__(self,other):
print('<<<<<<=========')
return (self.x,self.y,self.z,self.name)<=(other.x,other.y,other.z,other.name)
print(p3<=p4)
# <<<<<<=========
# True
6.遇到完全一样的Point,则需要定义__eq__
由于python还不认识Point,不知道怎么才算相等,直接使用==虽然不会报错,但是也得不到我们想要的结果
print(p5==p5_2)
# False
这里系统应该是将p5和p5_2作为 2 2 2个实体对象进行对待,虽然两者的内容一样,但是属于不同实体,或者说在内存中属于不同的位置,就认为不相等
我们的本意是比较p5和p5_2的内容,所以要进一步定义__eq__
def __eq__(self,other):
print('===============')
return (self.x,self.y,self.z,self.name)==(other.x,other.y,other.z,other.name)
print(p5==p5_2)
# ===============
# True
7.如果定义
>
,
>
=
,
!
=
>,>=,!=
>,>=,!=也是一样的
def __gt__(self,other): # >
pass
def __ge__(self,other): # >=
pass
def __ne__(self,other): # !=
pass
8.完整代码
class Point():
def __init__(self,x,y,z,name):
self.x=x
self.y=y
self.z=z
self.name=name
# def __lt__(self,other):
# print('<<<<<<<<<<<<<<<')
# return self.x
def __lt__(self,other):
print('<<<<<<<<<<<<<<')
return (self.x,self.y,self.z,self.name)<(other.x,other.y,other.z,other.name)
def __le__(self,other):
print('<<<<<<=========')
return (self.x,self.y,self.z,self.name)<=(other.x,other.y,other.z,other.name)
def __eq__(self,other):
print('===============')
return (self.x,self.y,self.z,self.name)==(other.x,other.y,other.z,other.name)
def __gt__(self,other): # >
pass
def __ge__(self,other): # >=
pass
def __ne__(self,other): # !=
pass
p1=Point(1,1,2,'p1')
p2=Point(2,2,3,'p2')
print(p1<p2)
p3=Point(1,4,5,'p3')
p4=Point(3,4,2,'p4')
print(p3<=p4)
p5=Point(1,2,3,'p5')
p5_2=Point(1,2,3,'p5')
# print(p5
print(p5==p5_2)
9.参考链接
python的魔法方法
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)