Implement a Password Manager Class in Python

Document 对象参考手册Python3 Examples

We will use Python to implement a simple password manager class. This class will allow users to store, retrieve, and delete passwords. The passwords will be stored in a dictionary, where the keys are account names and the values are passwords. For simplicity, the passwords will be stored in plain text, but in real-world applications, encryption should be used to protect passwords.

Example

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.")

Code Analysis:

  1. __init__The method initializes an empty dictionarypasswords, used to store accounts and passwords.
  2. add_passwordThe method accepts two parameters:accountandpassword, and adds them to thepasswordsdictionary.
  3. get_passwordThe method accepts one parameteraccount, and returns the password for that account. If the account does not exist, it returns a corresponding prompt message.
  4. delete_passwordThe method accepts one parameteraccount, and from thepasswordsdictionary, deletes the account and its password. If the account does not exist, it returns a corresponding prompt message.
  5. list_accountsThe method lists all accounts that have stored passwords. If no account has stored passwords, it returns a corresponding prompt message.

Output:

Example

# Example usage
pm = PasswordManager()
pm.add_password("email", "myemailpassword")
pm.add_password("bank", "mybankpassword")
print(pm.get_password("email"))  # Output: myemailpassword
pm.delete_password("bank")
pm.list_accounts()  # Output: Accounts with stored passwords: email

This simple password manager class can help you manage passwords for multiple accounts, and it can be extended as needed, for example, by adding encryption functionality or persistent storage.

Document 对象参考手册Python3 Examples

Other Extensions