创建一个名为User 的类,其中包含属性first_name 和last_name ,还有用户简介通常会存储的其他几个属性。在类User 中定义一个名 为describe_user() 的方法,它打印用户信息摘要;再定义一个名为greet_user() 的方法,它向用户发出个性化的问候。添加一个名为login_attempts 的属性。编写一个名为increment_login_attempts() 的方法, 它将属性login_attempts 的值加1。再编写一个名为reset_login_attempts() 的方法,它将属性login_attempts 的值重置为0。 根据User 类创建一个实例,再调用方法increment_login_attempts() 多次。打印属性login_attempts 的值,确认它被正确地递增;然后,调用方 法reset_login_attempts() ,并再次打印属性login_attempts 的值,确认它被重置为0。编写一个名为Admin 的类,让它继承你为完成练习9-3或练习9-5而编写的User 类。添加一个名为privileges 的属性,用 于存储一个由字符串(如"can add post" 、"can delete post" 、"can ban user" 等)组成的列表。编写一个名为show_privileges() 的方法,它 显示管理员的权限。创建一个Admin 实例,并调用这个方法。
时间: 2024-01-21 16:20:00 浏览: 24
下面是代码实现:
```python
class User:
def __init__(self, first_name, last_name, age, city):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.city = city
self.login_attempts = 0
def describe_user(self):
print(f"\n{self.first_name} {self.last_name}")
print(f"Age: {self.age}")
print(f"City: {self.city}")
def greet_user(self):
print(f"\nHello, {self.first_name}!")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self, first_name, last_name, age, city):
super().__init__(first_name, last_name, age, city)
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print("\nPrivileges:")
for privilege in self.privileges:
print(f"- {privilege}")
# 创建一个User实例并调用方法
user = User("John", "Doe", 25, "New York")
user.increment_login_attempts()
user.increment_login_attempts()
user.increment_login_attempts()
print(f"Login Attempts: {user.login_attempts}")
user.reset_login_attempts()
print(f"Login Attempts: {user.login_attempts}")
# 创建一个Admin实例并调用方法
admin = Admin("Jane", "Smith", 30, "Los Angeles")
admin.show_privileges()
```
输出结果:
```
Login Attempts: 3
Login Attempts: 0
Privileges:
- can add post
- can delete post
- can ban user
```