用数据结构编写一个可以添加新用户的可保存的需要密码的登录界面,设置一个管理员,管理员登录可以查看所有用户信息
时间: 2024-09-11 14:06:34 浏览: 37
为了实现这个功能,我们可以使用Python的字典(`dict`)数据结构来存储用户信息,其中包含用户名、密码和其他可能的属性(如是否为管理员)。我们将创建一个类`UserDatabase`来管理这些操作。
首先,我们定义一个基础的`User`类:
```python
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def is_valid_password(self, provided_password):
# 假设这里有一个简单的验证逻辑,例如明文存储密码或哈希对比
return provided_password == self.password
class Admin(User):
def __init__(self, username, password, *additional_info):
super().__init__(username, password)
self.additional_info = additional_info
```
接下来,我们需要`UserDatabase`类:
```python
class UserDatabase:
def __init__(self):
self.users = {}
def add_user(self, username, password, is_admin=False):
if is_admin:
user = Admin(username, password)
else:
user = User(username, password)
self.users[username] = user
def login(self, username, password):
if username in self.users and self.users[username].is_valid_password(password):
return True, "Logged in successfully"
else:
return False, "Invalid credentials"
def view_all_users(self, admin_username, admin_password):
if not self.login(admin_username, admin_password)[0]:
return "Failed to authenticate as administrator"
return [user for user in self.users.values()]
```
现在你可以使用这个类来执行所需的操作:
```python
db = UserDatabase()
# 添加普通用户
db.add_user("user1", "pass1")
# 添加管理员
db.add_user("admin", "adminpass", "extra_info")
# 登录普通用户
print(db.login("user1", "pass1")) # 输出:(True, 'Logged in successfully')
# 登录管理员
print(db.login("admin", "adminpass")) # 输出:(True, 'Logged in successfully')
admin_view = db.view_all_users("admin", "adminpass")
for user in admin_view:
print(user.username)
# 不成功的尝试
print(db.login("invalid", "password")) # 输出:(False, 'Invalid credentials')
```
阅读全文