如何在 python 中将函数参数作为模块的属性传递?

How can I pass a function parameter as an attribute of a module in python?

def hash(malware, hash):

        h = hashlib.hash()
        with open(malware,'rb') as f:
            chunk = 0
            while chunk != b'':
                chunk = f.read(1024)
                h.update(chunk)
        return h.hexdigest()

hash(file, 'sha1')
hash(file, 'sha256')

我想做的是使用 hashlib 模块的属性“sha1”和“sha256”作为函数参数。

这有可能吗?有没有办法做到这一点?

首先,不要使用 hash 作为函数名,因为它是标准库中的内置函数。 关于你的问题 - 从 hashlib 导入你想要的散列函数并将它们作为对象传递,而不是 str

from hashlib import sha1, sha256


def myhash(malware, hashfunc):

        h = hashfunc()
        with open(malware,'rb') as f:
            chunk = 0
            while chunk != b'':
                chunk = f.read(1024)
                h.update(chunk)
        return h.hexdigest()

myhash(file, sha1)
myhash(file, sha256)

如果你坚持要用str,就用getattr()

import hashlib

def myhash(malware, hashfunc):

        h = getattr(hashlib, hashfunc)()
        with open(malware,'rb') as f:
            chunk = 0
            while chunk != b'':
                chunk = f.read(1024)
                h.update(chunk)
        return h.hexdigest()

myhash(file, 'sha1')
myhash(file, 'sha256')

让我们把方法改成这样:

def hash(malware, h):
    with open(malware,'rb') as f:
        chunk = 0
        while chunk != b'':
            chunk = f.read(1024)
            h.update(chunk)
    return h.hexdigest()

hash1 = hashlib.sha1()
hash256 = hashlib.sha256()
hash(file, hash1)
hash(file, hash256)

因此,您只需通过函数参数传递 _hashlib.HASH(即 hash1hash256)。以下是输出示例:

>>> # test.txt --> hello world
>>> hash('test.txt', hash1) 
'2aae6c35c94fcfb415dbe95f408b9ce91ee846ed'
>>> hash('test.txt', hash256) 
'524857d0148721c24e3e7795e19ade0cdcf49f2a4dfbef2f1575d1208fa8c54f'