Implement a Password Manager Class in Python
We will implement a simple password manager class in Python. This class lets users store, retrieve, and delete passwords. Passwords are stored in a dictionary where the key is the account name and the value is the password. For simplicity the passwords are stored in plain text, but in a real application encryption should be used to protect them.
Example
class
PasswordManager:
def
init
(
self
)
:
self
.
passwords
=
{
}
def
add_password
(
self
,
account
,
password
)
:
self
.
passwords
[
account
]
=
password
(
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
]
(
f
"Password for {account} deleted successfully."
)
else
:
(
f
"No password found for {account}."
)
def
list_accounts
(
self
)
:
if
self
.
passwords
:
(
"Accounts with stored passwords:"
)
for
account
in
self
.
passwords
:
(
account
)
else
:
(
"No accounts with stored passwords."
)
Code analysis:
__init__The method initializes an empty dictionarypasswords, used to store accounts and passwords.add_passwordThe method takes two parameters:accountandpassword, and adds them to thepasswordsdictionary.get_passwordThe method takes one parameteraccount, and returns the password for that account. If the account does not exist, it returns a corresponding message.delete_passwordThe method takes one parameteraccount, and removespasswordsthe account and its password from the dictionary. If the account does not exist, it returns a corresponding message.list_accountsThe method lists all accounts with stored passwords. If no account has a stored password, it returns a corresponding message.
Output result:
Example
Example usage
pm
=
PasswordManager
(
)
pm.
add_password
(
"email"
,
"myemailpassword"
)
pm.
add_password
(
"bank"
,
"mybankpassword"
)
(
pm.
get_password
(
"email"
)
)
Output: myemailpassword
pm.
delete_password
(
"bank"
)
pm.
list_accounts
(
)
Output: Accounts with stored passwords: email
This simple password manager class helps you manage passwords for multiple accounts and can be extended as needed, for example by adding encryption or persistent storage.
Python3 Examples