用户简介通常会存储的其他几个属性。在类User 中定义一个名为describe_user()的方
法,它打印用户信息摘要;再定义一个名为greet_user()的方法,它向用户发出个性化
的问候。
创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
9-5 尝试登录次数:在为完成练习9-3 而编写的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。
class User():
def __init__(self, first_name, last_name, age):
self.first_name=first_name
self.last_name=last_name
self.age=age
self.login_attempts=0
def describe_user(self):
print("first name: "+self.first_name.title())
print("last name:"+self.last_name.title())
print("age: "+str(self.age))
print("login attempts: "+str(self.login_attempts))
def greet_user(self):
print("Hello, "+self.first_name.title()+" "+self.last_name.title())
def reset_login_attempts(self):
self.login_attempts=0
def increment_login_attempts(self):
self.login_attempts+=1
user1=User("Peter", "Liang", 19)
user1.greet_user()
i=0
while i<5:
user1.increment_login_attempts()
i+=1
user1.describe_user()
user1.reset_login_attempts()
user1.describe_user()
user2=User("Bill", "Herington", 47)
user2.greet_user()
user2.describe_user()
9-7 管理员:管理员是一种特殊的用户。编写一个名为Admin 的类,让它继承你为
完成练习9-3 或练习9-5 而编写的User 类。添加一个名为privileges 的属性,用于存
储一个由字符串(如"can add post"、"can delete post"、"can ban user"等)组成的
列表。编写一个名为show_privileges()的方法,它显示管理员的权限。创建一个Admin
实例,并调用这个方法。
9-8 权限:编写一个名为Privileges 的类,它只有一个属性——privileges,其中
存储了练习9-7 所说的字符串列表。将方法show_privileges()移到这个类中。在Admin
类中,将一个Privileges 实例用作其属性。创建一个Admin 实例,并使用方法
show_privileges()来显示其权限。
class User():
def __init__(self, first_name, last_name, age):
self.first_name=first_name
self.last_name=last_name
self.age=age
def describe_user(self):
print("first name: "+self.first_name.title())
print("last name:"+self.last_name.title())
print("age: "+str(self.age))
def greet_user(self):
print("Hello, "+self.first_name.title()+" "+self.last_name.title())
class Privileges():
def __init__(self, privileges):
self.privileges=privileges
def show_privileges(self):
for privilege in self.privileges:
print(privilege)
class Admin(User):
def __init__(self, first_name, last_name, age, pr):
super().__init__(first_name, last_name, age)
self.pr=pr
pr1=["can add post", "can delete post" , "can ban user"]
pr2=["can add post", "can delete post"]
pr3=["can add post"]
Pr1=Privileges(pr1)
Pr2=Privileges(pr2)
Pr3=Privileges(pr3)
p=Admin("Peter", "Liang", 19, Pr1)
b=Admin("Bill", "Herington", 47, Pr2)
j=Admin("James", "Jobs", 12, Pr3)
print(p.first_name+" "+p.last_name+":")
p.pr.show_privileges()
print(b.first_name+" "+p.last_name+":")
b.pr.show_privileges()
print(j.first_name+" "+p.last_name+":")
j.pr.show_privileges()