菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python hash() 函数

Python 内置函数 Python 内置函数


描述

hash() 用于获取取一个对象(字符串或者数值等)的哈希值。

语法

hash 语法:

hash(object)

参数说明:

  • object -- 对象;

返回值

返回对象的哈希值。

实例

以下实例展示了 hash 的使用方法:

>>>hash('test')# 字符串2314058222102390712 >>> hash(1)# 数字1 >>> hash(str([1,2,3]))# 集合1335416675971793195 >>> hash(str(sorted({'1':1})))# 字典7666464346782421378 >>>

Python 内置函数 Python 内置函数

AI 思考中...

3 篇笔记 写笔记

  1. #0

    忘忧北萱草

    wyb***qq.com

    34

    hash() 函数可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。

    hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。

    class Test:
     def __init__(self, i):
     self.i = i
    for i in range(10):
     t = Test(1)
     print(hash(t), id(t))

    输出结果:

    (277855628, 4445690048)
    (277855637, 4445690192)
    (277855628, 4445690048)
    (277855637, 4445690192)
    (277855628, 4445690048)
    (277855637, 4445690192)
    (277855628, 4445690048)
    (277855637, 4445690192)
    (277855628, 4445690048)
    (277855637, 4445690192)

    忘忧北萱草

    wyb***qq.com

    8年前 (2018年04月06日)
  2. #0

    冷梦

    149***[email protected]

    29

    hash() 函数的用途

    hash() 函数的对象字符不管有多长,返回的 hash 值都是固定长度的,也用于校验程序在传输过程中是否被第三方(木马)修改,如果程序(字符)在传输过程中被修改hash值即发生变化,如果没有被修改,则 hash 值和原始的 hash 值吻合,只要验证 hash 值是否匹配即可验证程序是否带木马(病毒)。

    name1='正常程序代码'
    name2='正常程序代码带病毒'
    print(hash(name1)) # 2403189487915500087
    print(hash(name2)) # -8751655075885266653

    冷梦

    149***[email protected]

    8年前 (2018年10月10日)
  3. #0

    cnvsss

    xia***[email protected]

    16

    对于 忘忧北萱草 的笔记进行一下补充:

    hash() 对对象使用时,所得的结果和对象的内容无关,只和对象的 id(),也就是内存地址有关。

    class foo(object):
     def __init__(self,x):
     self.x=x
     def get_x(self):
     return self.x
     def set_x(self,x):
     self.x=x
    test=foo(1)
    print(hash(test),test.get_x(),id(test))
    test.set_x(0)
    print(hash(test),test.get_x(),id(test))
    

    输出:

    3518817 1 56301072
    3518817 0 56301072

    cnvsss

    xia***[email protected]

    6年前 (2020年12月12日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /