9-8 权限
1. 项目
编写一个名为 Privileges 的类,它只有一个属性——privileges,其中存储了练习 9-7 所说的字符串列表。
将方法 show_privileges()移到这个类中。在 Admin类中,将一个 Privileges 实例用作其属性。
创建一个 Admin 实例,并使用方法show_privileges()来显示其权限。
2. 代码
class User(): """初始化用户属性""" def __init__(self, first_name, last_name, age, profession, login_attempts): self.first_name = first_name self.last_name = last_name self.age = age self.profession = profession """添加尝试登录次数属性""" self.login_attempts = login_attempts def describe_user(self): """用户信息描述方法""" print("User information: " + "\n" + self.first_name.title() + "." + self.last_name + "\n" + str(self.age) + "\n" + self.profession + ".") def greet_user(self): """问候方法""" print("Hello, " + self.first_name.title() + "." + self.last_name + ", welcome to ShangHai.\n") def increment_login_attempts(self): """尝试登录次数的增量方法""" self.login_attempts += 1 print(self.login_attempts) def reset_login_attempts(self): """重置登录次数方法""" self.login_attempts = 0 print(self.login_attempts) class Admin(User): def __init__(self, first_name, last_name, age, profession, login_attempts): super().__init__(first_name, last_name, age, profession, login_attempts) self.privileges = Privileges() class Privileges(): def __init__(self, privileges=("can add post", "can delete post", "can ban user")): self.privileges = privileges def show_privileges(self): print(self.privileges) admin = Admin('kevin', 'hou', 30, 'ee', 1) admin.privileges.show_privileges()
3. 执行结果
('can add post', 'can delete post', 'can ban user')