组织一段可重用代码的最佳实践是什么?

What is the best practice for organizing a piece of reusable code?

我正在构建一个基于文本的加密和解密游戏。有不同的级别,每个级别使用不同的密码来加密文本。我试图找出我给用户的一系列问题和提示(叙述)的最佳实践,以确定他是想练习、做测试、加密还是解密。每个级别 90% 的叙述都是相同的,所以我不想用相同的代码重复自己。最好的方法是什么?

我的第一个想法是定义一个包含通用脚本的函数,并将特定函数作为参数调用。 (这是我在下面尝试做的)。不过我好像运行 成范围问题了。当我调用 caesar() 函数作为 script() 函数中的参数之一时,我需要输入要加密的文本,但用户直到 script()功能已经开始运行ning.

我是否应该使用 class 来定义程序的叙述部分,然后继承到更具体的类型?

还是我应该在不同层次上重复叙述代码?

叙述如下script():

def script(encrypt, decrypt):
    """Asks user if they want to practice (encode or decode) or take the
    test, and calls the corresponding function."""
encrypt = encrypt
decrypt = decrypt

    while True:
        print('Type Q to quit.  Type M to return to the main menu.')
        prac_test = input('would you like to practice or take the test? P/T')
        if prac_test.lower() == 'p':
            choice = input('Would you like to encrypt or decrypt? E/D ')
            if choice.lower() == 'e':
                text = input('Enter the text you would like to encode: ')
                encrypt
            elif choice.lower() == 'd':
                text = input('Enter the text you would like to decode: ')
                key = int(input('Enter the key: '))
                decrypt
            else:
                print('You must enter either "E" or "D" to encode or decode a
                  text. ')
        elif prac_test.lower() == 't':
            text = random.choice(text_list)
            encrypted_text = encrypt
            print(encrypted_text[0])
            answer = input('s/nCan you decode this string? ')
            if answer.lower() == ran_str.lower():
                print('Congrats! You solved level 1!\n')
                pass
            elif answer != ran_str:
                print("Sorry, that's not correct.  Why don't you practice some
                   more?\n")
                script(encrypt, decrypt)
        elif prac_test.lower() == 'q':
            exit()
        elif prac_test.lower() == 'm':
            break
        else:
            print('Please enter a valid choice.')

这是使用凯撒密码的关卡之一:

def caesar(mode, text, key=None):
    """
...
The dictionaries that convert between letters and numbers are stored in the .helper file, imported above.
    """
    mode = mode
    if mode == 'encrypt':
        key = random.randint(1, 25)
    elif mode == 'decrypt':
        key = key
    str_key = str(key)
    text = text.lower()
    # converts each letter of the text to a number
    num_list = [alph_to_num[s] if s in alph else s for s in text]
    if mode == 'encrypt':
        # adds key-value to each number
        new_list = [num_to_alph[(n + key) % 26] if n in num else n for n in
                    num_list]
    elif mode == 'decrypt':
        # subtracts key-value from each number
        new_list = [num_to_alph[(n - key) % 26] if n in num else n for n in
                    num_list]
    new_str = ''
    for i in new_list:
        new_str += i
    return new_str, str_key

下面是我会尝试将它们一起使用的人:

script(caesar('encrypt' text), caesar('decrypt', text, key))

请指导我组织这个可重复使用的叙述代码的最佳方式。

您可能想使用多个函数:

  • 一个,我们将调用 main(),以显示菜单并与用户交互
  • A class Caesar,公开两个函数:encrypt(text, key)decrypt(text, key)

一个简单的程序可能看起来像

def main():
    print("Welcome to the game")
    action = input("Would you like to encrypt or decrypt a text [e/d]">).lower()
    text = input("What is the text you want to test on ? >")
    key = input("What's your key")
    # optionnaly, ask for what kind of cipher they want to use, then use a dict to chose the right class
    cipher = Caesar()
    if action == "e":
         output = cipher.encrypt(text, key=key)
    else:
         output = cipher.decrypt(text, key=key)

    print(output)
    print("Thanks for playing!")