在 python 中,内置函数hash()用于获取给定对象的哈希值。为了在字典查找时比较字典关键字,使用这些整数哈希值。实际上hash()方法调用的是对象的 __hash__() 方法。

Hashable 类型: bool int long float string Unicode tuple code 对象
不可散列类型:字节数组列表集合字典*内存视图
 **hash(object)** #Where object can beinteger, string, float etc. 
接受单个参数。相等的数值将具有相同的哈希值,而与它们的数据类型无关。
| 参数 | 描述 | 必需/可选 | 
|---|---|---|
| 目标 | 要返回其哈希值的对象(整数、字符串、浮点) | 可选择的 | 
hash()方法返回对象的哈希值(如果有)。对象采用自定义__hash__()方法,它将返回值截断为 Py_ssize_t 的大小。
| 投入 | 返回值 | | 目标 | 哈希值 |
hash()方法的示例hash()在 Python 中是如何工作的? # hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:',hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python')) 
输出:
Hash for 181 is: 181
Hash for 181.23 is: 530343892119126197
Hash for Python is: 2230730083538390373 
hash()? # tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels)) 
输出:
The hash is: -695778075465126279 
__hash__()为自定义对象设置__hash__() class Person:
    def __init__(self, age, name):
        self.age = age
        self.name = name
    def __eq__(self, other):
        return self.age == other.age and self.name == other.name
    def __hash__(self):
        print('The hash is:')
        return hash((self.age, self.name))
 pers 'Adam')
print(hash(person)) 
输出:
The hash is:
3785419240612877014             
                名称栏目:创新互联Python教程:Pythonhash()
                
                网站URL:http://www.csdahua.cn/qtweb/news28/354978.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网