python md5,d.update(strParam).hexdigest() 返回 NoneType,为什么?

0 投票
3 回答
6853 浏览
提问于 2025-04-16 20:41
>>> d = md5.new()
>>> d.update('a').hexdigest()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'hexdigest'

这样做是可以的 -

>>> d = md5.new()
>>> d.update('a')
>>> d.hexdigest()
'0cc175b9c0f1b6a831c399e269772661'

有没有关于如何简化Python代码的解释?

3 个回答

2

好吧,因为更新操作没有返回值(在Python中,默认返回值是None),所以调用 update(arg).<anything> 一定会失败。有些库的最后一行代码会写 return self,如果这里也是这样的话,你的第一个代码示例就能正常工作了。

用分号可以把所有代码写在一行上:

d = md5.new(); d.update('a'); d.hexdigest()

不过一般不推荐这样做。

6

你可以这样做:

md5.new('a').hexdigest()

这段话是从文档中改写过来的:

new(arg) 会返回一个新的 md5 对象。如果有 arg 这个参数,那么会调用 update(arg) 方法。


不过,md5 已经不推荐使用了。
建议使用 hashlib

补充说明:
md5 还有一些问题,所以根据你的需求,你可能想用一个更安全的哈希函数,比如 SHA-256:

import hashlib
hashlib.sha256('a').hexdigest()

请注意,SHA-256 的计算时间会更长,所以如果你有时间限制,可能就不太适合使用这个方法。

4

你想要的是这个:

import hashlib
hashlib.md5('a').hexdigest()

注意:不要单纯使用MD5来保证安全。

  • 如果你是在处理密码,建议使用scrypt或bcrypt。
  • 如果你是在验证消息的真实性,使用HMAC。
  • 如果你是在检查文件的完整性,可以考虑使用SHA2或更新的版本。

撰写回答