Python 内建函数 - hash(object)

Python的内置函数hash()用于获取对象的哈希值,主要用于字典查找。相等数值的哈希值相同,即使类型不同。自定义__hash__()方法时,返回值会根据主机位宽截断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Note For object’s with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine. See __hash__() for details.

直译

返回object的哈希值(如果它有一个的话)。哈希值是整数,它们用于在字典查找时快速匹配字典键。相等的数字值具有同样的哈希值(即便它们属于不同的类型,例如1和1.0)

注意:对象自定义的__hash__()方法,hash() 基于主机的位宽来截断返回值,详情见__hash__()。

实例

>>> class 优快云:
    def foobar(self):
        print('Hello 优快云er!')
>>> hash(优快云)
4561779

>>> class 优快云:
    def __init(self):
        self.name = '优快云er'
        self.nick = 'Fans'
        self.color = 'Red'
    def __hash__(self):
        return hash((self.name, self.nick, self.color))
    def foobar(self):
        print('Hello 优快云er!')
>>> hash(优快云)
4561807

拓展阅读

__hash__()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值