设计一个表示用户的User类,类中的变量有用户名、口令和记录用户个数的变量,定义类的构造方法、获取和设置用户名、口令的方法和返回帐户信息(第几个帐户,帐户名,密码)的方法
时间: 2024-05-06 15:21:58 浏览: 210
java类和对象实验报告.pdf
以下是Python代码实现:
```python
class User:
user_count = 0 # 记录用户个数的变量
def __init__(self, username, password):
self.username = username
self.password = password
User.user_count += 1
def get_username(self):
return self.username
def set_username(self, username):
self.username = username
def get_password(self):
return self.password
def set_password(self, password):
self.password = password
def get_account_info(self):
return "Account {} - username: {}, password: {}".format(User.user_count, self.username, self.password)
```
使用示例:
```python
# 创建两个用户
user1 = User("Alice", "123456")
user2 = User("Bob", "654321")
# 获取和设置用户名、口令
print(user1.get_username()) # 输出: Alice
user1.set_username("NewAlice")
print(user1.get_username()) # 输出: NewAlice
print(user2.get_password()) # 输出: 654321
user2.set_password("NewPass")
print(user2.get_password()) # 输出: NewPass
# 返回帐户信息
print(user1.get_account_info()) # 输出: Account 1 - username: NewAlice, password: 123456
print(user2.get_account_info()) # 输出: Account 2 - username: Bob, password: NewPass
```
阅读全文