Python 组织一段可重用代码的最佳实践是什么?
我正在构建一个基于文本的加密和解密游戏。有不同的级别,每个级别使用不同的密码加密文本。我试图找出一系列问题和提示(叙述)的最佳实践,我给用户提供这些问题和提示,以确定他是否想要练习、进行测试、加密或解密。每个级别90%的叙述都是相同的,所以我不想用相同的代码重复我自己。最好的方法是什么 我的第一个想法是定义一个包含通用脚本的函数,并将特定函数作为参数调用。(这就是我在下面尝试做的事情)。但我似乎遇到了范围问题。当我调用Python 组织一段可重用代码的最佳实践是什么?,python,oop,code-organization,Python,Oop,Code Organization,我正在构建一个基于文本的加密和解密游戏。有不同的级别,每个级别使用不同的密码加密文本。我试图找出一系列问题和提示(叙述)的最佳实践,我给用户提供这些问题和提示,以确定他是否想要练习、进行测试、加密或解密。每个级别90%的叙述都是相同的,所以我不想用相同的代码重复我自己。最好的方法是什么 我的第一个想法是定义一个包含通用脚本的函数,并将特定函数作为参数调用。(这就是我在下面尝试做的事情)。但我似乎遇到了范围问题。当我调用caesar()函数作为script()函数中的一个参数时,我需要输入要加密的
caesar()
函数作为script()
函数中的一个参数时,我需要输入要加密的文本,但是在script()
函数开始运行之前,用户不会提供此文本
我应该使用类来定义程序的叙述部分,然后继承到更具体的类型吗
还是我应该在不同的层面重复叙述代码
下面是叙述性的脚本()
:
下面是使用凯撒密码的一个级别:
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()
,以显示菜单并与用户交互
- 一个类
Caesar
,它公开了两个函数:加密(文本,密钥)
和解密(文本,密钥)
一个简单的程序可能看起来像
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!")
请修复缩进我刚刚修复了缩进。def脚本(加密、解密):
仍然有不可靠的缩进。while
循环大概是函数的一部分?
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!")