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

时间:2019-01-14 22:25:46

标签: python oop code-organization

我正在构建一个基于文本的加密和解密游戏。有不同的级别,并且每个级别使用不同的密码来加密文本。我正在尝试为用户提供一系列问题和提示的最佳实践(叙述),以确定用户是否要练习,进行测试,加密或解密。每个级别90%的叙述都是相同的,所以我不想重复相同的代码。最好的方法是什么?

我的第一个想法是定义一个包含通用脚本的函数,并将特定的函数作为参数调用。 (这是我下面尝试做的)。但是我似乎遇到了范围问题。当我将caesar()函数用作script()函数的参数之一时,我需要输入要加密的文本,但是直到{{1} }功能已经开始运行。

我应该使用script()定义程序的叙述部分,然后继承为更特定的类型吗?

还是我应该在不同级别重复叙述代码?

这里是叙述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

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

1 个答案:

答案 0 :(得分:2)

您可能想使用多种功能:

  • 一个,我们称为main(),用于显示菜单并与用户互动
  • 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!")