|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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呢?
本帖最后由 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
|
|