【发布时间】:2020-08-02 06:07:43
【问题描述】:
我刚刚创建了我的第一个 Python 项目。我确信可以进行很多改进,但我有一个关于如何更改我的代码的具体问题。
我一直在读到使用全局变量是不明智的(出于安全考虑)。但我不确定如何使多个函数一起工作(即使用相同的变量),除非它们是全局的。
下面的程序做了三件事:
- 生成密码。
- 加密该密码。
- 解密密码。
但是,我只在第 2 部分声明了全局变量来加密密码。
我的问题是:如何更改代码以避免使用全局变量?我粘贴了下面的所有代码以供参考,但全局变量在def listToString() 和def passEncryptor(): 中声明。
import random
#variables to hold a list and a string
Password = []
Encrypted = ''
#variables to hold the specific characters
#to use in creating the password
a = 'abcdefghijklmnopqrstuvwxyz'
b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
c = '0123456789'
d = '!@#$%^&*()'
#variable holds all possible values
#that could be found in the password
e = a + b + c + d
#variables will randomize the password length
sm = random.randint(2,3)
lg = random.randint(3,4)
#function generates a randomized password
def passwordGenerator() :
#append elements from variables a - d
#to the Password variable
for x in range(sm) :
Password.append(random.choice(a))
for x in range(sm) :
Password.append(random.choice(b))
for x in range(lg) :
Password.append(random.choice(c))
for x in range(sm) :
Password.append(random.choice(d))
#randomize the order of the elements
random.shuffle(Password)
#ensure the first element is a letter
Password.insert(0, random.choice(a))
#print to show that the program worked
print(Password)
#call function to generate a randomized password
passwordGenerator()
#function to store 5 random elements in a string
def listToString() :
#can't seem to get this to work
#without using a global variable
global rand5
rand5 = ''
x = random.choices(e, k=5)
for val in x :
rand5 += val
return rand5
#for each element in the password
#add the random 5 elements from listToString()
def passEncryptor():
global tempPass
tempPass = ''
for val in Password :
#gets 5 new random elements
listToString()
#concatenate the random elements
#with the real password
tempPass += val + rand5
print(tempPass)
passEncryptor()
#function to unencrypt an encrypted password
def passDecryptor():
#convert the encrypted string to a list
encryptedList = []
for val in tempPass :
encryptedList.append(val)
#remove the random 5 elements
decrypt = encryptedList[::6]
decrypted = ''
#convert back to a string
for val in decrypt :
decrypted += val
print(decrypted)
passDecryptor()
【问题讨论】:
-
请将此减少并增强为预期的MRE。还要查找避免全局变量的常用方法,并在您的问题中参考您的 remaining 问题。
-
以一种方式在程序顶部定义这些全局变量,如果您不定义它们它们将运行良好,请使用赋值运算符保存函数的输出,例如 passs = encrpt()
-
使用全局变量,早就considered harmful了,各种原因不一定只是安全问题。两个主要问题是它使代码更难调试和维护。
-
避免全局变量的一种非常好的常用方法是遵循 Python 完全支持的 OOP (Object-oriented programming) 范式。
标签: python function variables global