平等和身份-python
对于下面定义的用户定义python平等和身份-python,python,python-3.x,Python,Python 3.x,对于下面定义的用户定义pythonclass,a==b为False >>> class Account(): def __init__(self, account_holder): self.balance = 0 self.holder = account_holder >>> a = Account('Jim') >>> b = Account('Jim') >>
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
==
)的工作class对象的哪个方法
为python中任何用户定义类的所有实例提供标识您必须通过重写类中的_ueq_u方法来实现类相等。有关更多详细信息,请参见此处: 在您的特定情况下,类似以下内容:
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
如果您需要更多示例,请提供好的示例
编辑:正如@SergeBallesta在评论中所提到的,以及文档中所敦促的,重写uu eq u()方法的反射是一个好主意,它是u ne u()。重写
\uu eq u
和\uu ne u
方法
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
关于身份是操作员<如果a
和b
都持有对同一对象的引用,则code>a是b
将是True
a = b
print a is b # return True
print a is c # return False
您可以阅读类似的函数。对于identity,我需要覆盖什么?您不能覆盖identity。这没有任何意义。两个对象要么是同一对象,要么不是。假装两个不同的对象是相同的是疯狂的。@kindall firstobject.\uuu hash\uuu()
实际上返回用户定义类的所有实例的标识,对吗?如果是,那么对象的返回类型/typesizebits是什么?在java中,必须覆盖标识,因为public int hashCode()
返回32位整数,尽管我创建了超过2^32个对象。@overexchange\uuuu hash\uuu()返回整数。这只是一种设计选择,除非被重写,否则默认情况下_hash__;()函数使用从Cpython中的id(obj)派生的结果,id(obj)是对象的地址。另一方面,“is”操作符测试它在内存中是否是完全相同的位置,简单地说。检查这个问题,它很好地解释了这一点:Python中的整数可以是任意位数。无论如何,两个不同的对象拥有相同的散列是完全合法的。我不认为这是身份主题的重复问题