判断两个类相等
class student(object):def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def __eq__(self, *args, **kwargs):
return object.__eq__(self, *args, **kwargs)
like = student("like",25,"male")
xue = student("xue",23,"female")
dong = student("like",25,"male")
print(like is xue) #False
print(like is dong) #False
print(like == dong) #False
为啥最后一个print也是false呢? 参考:https://blog.csdn.net/sinat_38682860/article/details/111315479 本帖最后由 isdkz 于 2023-2-20 10:52 编辑
因为对象的魔法方法 __eq__ 的默认行为也是判断两个对象的地址是否相等,所以 == 和 is 得到的是一样的结果,
如果你要根据属性来判断的话改成这样:
class student(object):
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def __eq__(self, value, /):
return self.__dict__ == value.__dict__
like = student("like",25,"male")
xue = student("xue",23,"female")
dong = student("like",25,"male")
print(like is xue) #False
print(like is dong) #False
print(like == dong) #True
页:
[1]