对于以下定义的用户定义的python class
,a == b
为False
>>> class Account():
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
>>> a = Account('Jim')
>>> b = Account('Jim')
>>> a is b
False
>>> a == b
False
但在以下情况下,相等(==
)运算符显示True
>>> lst1 = [1, 2]
>>> lst2 = [1, 2]
>>> lst1 == lst2
True # this is true
>>> lst1 is lst2
False
>>> str1 = 'abc'
>>> str2 = 'abc'
>>> str1 == str2
True # this is true
>>> str1 is str2
True
>>> tup1 = (1, 2)
>>> tup2 = (1, 2)
>>> tup1 == tup2
True # this is true
>>> tup1 is tup2
False
当在python中定义用户定义的类时,如何理解相等运算符(==
)的工作?
class object
哪种方法为python中任何用户定义类的所有实例提供标识?
答案 0 :(得分:2)
您必须通过覆盖类中的__eq__方法来实现类平等。有关详情,请参阅此处:__eq__
在您的特定情况下,类似这样的事情:
class Account():
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
def __eq__(self, other):
return self.holder == other.holder
def __ne__(self, other):
return not self.__eq__(other)
现在a == b
应该返回True。
如果您想要更多示例How to override comparison operators,请提供更好的示例。
编辑:正如@SergeBallesta在评论中提到的那样,并且正如文档所敦促的那样,最好覆盖__eq __()方法的反射,即__ne __()。
答案 1 :(得分:1)
覆盖__eq__
和__ne__
方法。
class Account():
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
def __eq__(self, other):
"""Override the default equals"""
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
def __ne__(self, other):
"""non-equality"""
return not self.__eq__(other)
a = Account('Jim')
b = Account('Jim')
print a == b
c = Account('Not Jim')
print a == c
输出:
True
False
关于身份is
运营商。如果a is b
和True
都持有对同一对象的引用,则a
将为b
。
a = b
print a is b # return True
print a is c # return False
您可以阅读类似的功能here。