Python reflection application scenario (1)

    Understand the basic usage of the four functions in reflection . So what's the use of reflection? What is its application scenario? The answer is that you can use reflection when you are not sure whether the required properties and functions exist. Another important role is to improve the scalability and maintainability of the code. Suppose we maintain all encryption algorithms in a module called encryption, and allow users of this module to add more encryption algorithms to this module.

The content of the encryption module is as follows:

import hashlib
import os
import sys
def md5(content=None):
    """生成字符串的SHA256值"""
    if content is None:
        return ''
    md5_gen = hashlib.md5()
    md5_gen.update(content.encode('utf-8'))
    md5code = md5_gen.hexdigest()
    return md5code


def sha256(content=None):
    """生成字符串的SHA256值"""
    if content is None:
        return ''
    sha256_gen = hashlib.sha256()
    sha256_gen.update(content.encode('utf-8'))
    sha256code = sha256_gen.hexdigest()
    return sha256code


def sha256_file(filename):
    """生成文件的SHA256值"""
    if not os.path.isfile(filename):
        return ""
    sha256gen = hashlib.sha256()
    size = os.path.getsize(filename)  # 获取文件大小,单位是Byte
    with open(filename, 'rb') as fd:  # 以二进制方式读取文件
        while size >= 1024 * 1024:  # 当文件大于1MB时分块读取文件内容
            sha256gen.update(fd.read(1024 * 1024))
            size -= 1024 * 1024
        sha256gen.update(fd.read())
    sha256code = sha256gen.hexdigest()
    return sha256code


def md5_file(filename):
    """生成文件的MD5值"""
    if not os.path.isfile(filename):
        return ""
    md5gen = hashlib.md5()
    size = os.path.getsize(filename)  # 获取文件大小,单位是Byte
    with open(filename, 'rb') as fd:
        while size >= 1024 * 1024:  # 当文件大于1MB时分块读取文件内容
            md5gen.update(fd.read(1024 * 1024))
            size -= 1024 * 1024
        md5gen.update(fd.read())
    md5code = md5gen.hexdigest()
    return md5code


def encrypt_something(something, algorithm):
    """
    通用加密算法
    :param something: 待加密的内容,字符串或者文件
    :param algorithm: 加密算法
    :return:  加密后的内容
    """
    result = ""
    if algorithm == "md5":
        result = md5(something)
    elif algorithm == "sh256":
        result = sha256(something)
    elif algorithm == "sh256_file":
        result = sha256_file(something)
    elif algorithm == "md5_file":
        result = md5_file(something)
    return result

Among them, the encrypt_something function provides a general encryption algorithm, and the caller needs to pass in the content to be encrypted and the encryption algorithm, so that when the caller uses the encryption.py module, he only needs to import the encrypt_something function. like this:

import encryption
print(encryption.encrypt_something("learn_python_by_coding", "sh256"))
print(encryption.encrypt_something("learn_python_by_coding", "md5"))

By analyzing the encrypt_something function, it is found that when we add more encryption algorithms in the encryption.py module, we need to modify the encrypt_something function and add a new if branch to it. With the increase of encryption algorithms, the branches of the encrypt_something function will become more and more many.

After learning reflection, the encrypt_something code part can be written like this:

def encrypt_something(something, algorithm):
    """
    通用加密算法
    :param something: 待加密的内容,字符串或者文件
    :param algorithm: 加密算法
    :return:  加密后的内容
    """
    this_module = sys.modules[__name__]
    if hasattr(this_module, algorithm):
        algorithm = getattr(this_module, algorithm)
        result = algorithm(something)
    else:
        raise ValueError("Not support {} algorithm".format(algorithm))
    return result

Compared with the previous if branch statement method, the reflection is more concise and clear, and the maintainability is stronger. To add a new encryption method, you only need to add more encryption algorithms in the encryption.py module. The encrypt_something code does not need any change.

9ddd06a8ce5e09d171211c34091e9f23.png

Guess you like

Origin blog.csdn.net/qq_36502272/article/details/124521842