#!/usr/bin/env python3
from hashlib import sha256
def produce_digest_char_by_char(word):
d=sha256();print(d.hexdigest())
for b in word:
#d=d.update(b.encode()):print(d.hexdigest())#AttributeError: 'NoneType' object has no attribute 'hexdigest'
d.update(b.encode());print(d.hexdigest())#This works fine
return d.hexdigest()
print(sha256().hexdigest())
print(sha256(b"lana").hexdigest())
print(produce_digest_char_by_char("lana"))
注释掉的行不起作用,给我这个错误:
AttributeError: 'NoneType' object has no attribute 'hexdigest'
。通过反复试验,我找出了代码中的修复方法,但我想知道为什么 Python 会这样? help(sha256)
提供此信息
Returns a sha256 hash object; optionally initialized with a string
在此信息中,没有任何内容表明
sha256
可能会返回 None
。
您收到 Nonetype 错误的原因是因为命令是
d.update(b.encode())
但你正在尝试 d = d.update(b.encode())
并且 d.update(..)
返回 None