class person(object): def __init__(self,name,age): self.name=name self.age=age def __eq__(self, other): print('__eq__方法被调用了, other=',other) if self.name==other.name and self.age==other.age: return True else:###k可以不写 return False #return self.name==other.name and self.age==other.age #1、调用__new__方法申请内存空间 p1=person('张三',18) #1、调用__new__方法申请内存空间 p2=person('张三',18) p3=person('张三',19) #p1 和p2是同一个对象吗?? #不是一个对象,是两块内存空间 #怎样比较两个对象为同一对象?比较的是内存地址 print('0x%X' %id(p1))#0x14DB15F6BB0 print('0x%X' %id(p2))#0x14DB1625BE0 #身份运算符:可以用来判断两个对象是否为同一对象 print(p1 is p2)#False print('_'*88) num1=[1,2,3] num2=[1,2,3] print(num1 is num2)#False print(num1==num2)#True ##is 比较两个对象的内存地址, ##==是比较值的——不是真的比较值————而是调用__eq__方法,获取这个方法的比较结果 print('_'*88) #eq方法如果不重写,默认比较的依然是内存地址 print(p1==p2)#False本质是调用p1.__eq__(p2)#true print('_'*88) print(p1==p3)#False
结果:
D:\pythonss\venv\Scripts\python.exe D:/pythonss/魔法方法补充.py
0x1F0969B6BB0
0x1F0969E5BE0
False
________________________________________________________________________________________
False
True
________________________________________________________________________________________
__eq__方法被调用了, other= <__main__.person object at 0x000001F0969E5BE0>
True
________________________________________________________________________________________
__eq__方法被调用了, other= <__main__.person object at 0x000001F0969F0250>
False
Process finished with exit code 0