在我的函数中是否有少用if语句的方法?

2024-10-03 19:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用名为password的类和名为generate的方法创建了一个随机密码生成器

我的程序正常工作。它根据用户对长度、大小写、数字和特殊字符的偏好生成随机密码

我只是想知道是否有办法重构我用来确定程序将生成何种密码的大量if statements

我能提出的任何其他改进建议也会很有帮助。非常感谢

代码:

import random
import string

class password:
    def __init__(self, length, string_method, numbers=True, special_chars=False):
        self.length = length
        self.string_method = string_method
        self.numbers = numbers
        self.special_chars = special_chars

    def generate(self, iterations):

        # Checking what type of string method the user has asked for

        if self.string_method == 'upper':
            stringMethod = string.ascii_uppercase
        elif self.string_method == 'lower':
            stringMethod = string.ascii_lowercase
        elif self.string_method == 'both':
            stringMethod = string.ascii_letters

        # Checking if the user has asked for numbers or not

        if self.numbers == True:
            stringNumbers = string.digits
        elif self.numbers == False:
            stringNumbers = ''

        # Checking if the user has asked for special characters or not

        if self.special_chars == True:
            stringSpecial = string.punctuation
        elif self.special_chars == False:
            stringSpecial = ''

        characters = stringMethod + stringNumbers + stringSpecial

        # Generating the password

        for p in range(iterations):
            output_password = ''
            for c in range(self.length):
                output_password += random.choice(characters)
            print(output_password)

# Test

password1 = password(20, 'lower', True, False) # password length = 20, string method is lowercase, numbers are true and special characters are false
password1.generate(3) # generate the random password 3 times```

Tags: theselffalsetrueforstringifpassword
3条回答

你没有那么多的if语句,你有不必要的变量。不要在末尾追加all,只需在if语句中追加字符列表即可

characters = ""
if self.string_method == 'upper':
    characters += string.ascii_uppercase

那么您就根本不需要大多数elif/else语句了

您可以将其重写为使用map而不是if/else进行初始检查

    methods_map = {
        "upper": string.ascii_uppercase,
        "lower": string.ascii_lowercase,
        "both": string.ascii_letters
    }
    string_method = methods_map[self.string_method]
    string_numbers = string.digits if self.numbers else ''
    string_special = string.punctuation if self.special_chars else ''

    characters = string_method + string_numbers + string_special

对于特殊值和数字,可以使用类似string_numbers = ['', string.digits][self.numbers]的if语句,但我不推荐使用它,因为它会使代码的可读性大大降低

首先,不要这样做:

if something == True:
    pass
elif something == False:
    pass

您可以这样做:

if something:
    pass
else:
    pass

您可以将stringSpecialstringNumbers初始化为空字符串以省略else块:

stringNumbers = ''
stringSpecial = ''

if self.numbers:
    stringNumbers = string.digits

if self.specialChars:
    stringSpecial = string.punctuation

您还可以使用dict删除第一个if-elif块,如下所示:

methods = {
    'upper': string.ascii_uppercase,
    'lower': string.ascii_lowercase,
    'both': string.ascii_letters
}

stringMethod = methods[self.string_method]

相关问题 更多 >