使用 Python 实现一个密码管理器类
我们将使用 Python 实现一个简单的密码管理器类。这个类将允许用户存储、检索和删除密码。密码将存储在一个字典中,其中键是账户名称,值是密码。为了简单起见,密码将以明文形式存储,但在实际应用中,应该使用加密技术来保护密码。
实例
class PasswordManager:
def __init__(self):
self.passwords = {}
def add_password(self, account, password):
self.passwords[account] = password
print(f"Password for {account} added successfully.")
def get_password(self, account):
if account in self.passwords:
return self.passwords[account]
else:
return f"No password found for {account}."
def delete_password(self, account):
if account in self.passwords:
del self.passwords[account]
print(f"Password for {account} deleted successfully.")
else:
print(f"No password found for {account}.")
def list_accounts(self):
if self.passwords:
print("Accounts with stored passwords:")
for account in self.passwords:
print(account)
else:
print("No accounts with stored passwords.")
def __init__(self):
self.passwords = {}
def add_password(self, account, password):
self.passwords[account] = password
print(f"Password for {account} added successfully.")
def get_password(self, account):
if account in self.passwords:
return self.passwords[account]
else:
return f"No password found for {account}."
def delete_password(self, account):
if account in self.passwords:
del self.passwords[account]
print(f"Password for {account} deleted successfully.")
else:
print(f"No password found for {account}.")
def list_accounts(self):
if self.passwords:
print("Accounts with stored passwords:")
for account in self.passwords:
print(account)
else:
print("No accounts with stored passwords.")
代码解析:
__init__
方法初始化了一个空字典passwords
,用于存储账户和密码。add_password
方法接受两个参数:account
和password
,并将它们添加到passwords
字典中。get_password
方法接受一个参数account
,并返回该账户的密码。如果账户不存在,则返回相应的提示信息。delete_password
方法接受一个参数account
,并从passwords
字典中删除该账户及其密码。如果账户不存在,则返回相应的提示信息。list_accounts
方法列出所有存储了密码的账户。如果没有账户存储密码,则返回相应的提示信息。
输出结果:
实例
# 示例使用
pm = PasswordManager()
pm.add_password("email", "myemailpassword")
pm.add_password("bank", "mybankpassword")
print(pm.get_password("email")) # 输出: myemailpassword
pm.delete_password("bank")
pm.list_accounts() # 输出: Accounts with stored passwords: email
pm = PasswordManager()
pm.add_password("email", "myemailpassword")
pm.add_password("bank", "mybankpassword")
print(pm.get_password("email")) # 输出: myemailpassword
pm.delete_password("bank")
pm.list_accounts() # 输出: Accounts with stored passwords: email
这个简单的密码管理器类可以帮助你管理多个账户的密码,并且可以根据需要进行扩展,例如添加加密功能或持久化存储。
点我分享笔记