文章目录
0 前言
《Python编程:从入门到实践》 第9章 类 练习题–类User
1 练习题描述
练习9-3 用户
创建一个名为User的类,其中包含属性first_name和last_name,还有用户简介通常会存储的其他几个属性。在类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。
练习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()来显示其权限。
练习9-11 导入Admin类
以为完成练习9-8而做的工作为基础。将User、Privileges和Admin类存储在一个模块中,再创建一个文件,在其中创建一个Admin实例并对其调用方法show_privileges(),以确认一切都能正确地运行。
2 自编程序
2.1 User.py
class User:
def __init__(self, first_name, last_name, username, login_attempts):
self.first_name = first_name
self.last_name = last_name
self.username = username
self.login_attempts = login_attempts
def describe_user(self):
print(f"{self.first_name} {self.last_name}'s username is: {self.username}")
def greet_user(self):
print(f"Hello, {self.first_name} {self.last_name}")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
def show_login_attempts(self):
print(f"Now your login attempts are: {self.login_attempts}")
class Privileges:
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
if self.privileges:
print("Your privileges are:")
for privilege in self.privileges:
print("-" + str(privilege))
class Admin(User):
def __init__(self, first_name, last_name, username, login_attempts):
super().__init__(first_name, last_name, username, login_attempts)
self.privileges = Privileges()
2.2 main.py
from user import User, Admin
user1 = User("A", "B", 'Abb', 5)
user1.describe_user()
user1.greet_user()
user1.increment_login_attempts()
user1.show_login_attempts()
user1.reset_login_attempts()
user1.show_login_attempts()
user2 = User("C", "D", 'Cdd', 0)
user2.describe_user()
user2.greet_user()
user2.increment_login_attempts()
user2.show_login_attempts()
admin1 = Admin("E", "F", 'EfF', 10)
admin1.describe_user()
admin1.greet_user()
admin1.privileges.privileges = ['can add post', 'can delete post']
admin1.privileges.show_privileges()
2.3 Output
A B's username is: Abb
Hello, A B
Now your login attempts are: 6
Now your login attempts are: 0
C D's username is: Cdd
Hello, C D
Now your login attempts are: 1
E F's username is: EfF
Hello, E F
Your privileges are:
-can add post
-can delete post
3 练习9-11 导入Admin类 参考答案
3.1 user.py
"""A collection of classes for modeling users."""
class User():
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
self.login_attempts = 0
def describe_user(self):
"""Display a summary of the user's information."""
print("\n" + self.first_name + " " + self.last_name)
print(" Username: " + self.username)
print(" Email: " + self.email)
print(" Location: " + self.location)
def greet_user(self):
"""Display a personalized greeting to the user."""
print("\nWelcome back, " + self.username + "!")
def increment_login_attempts(self):
"""Increment the value of login_attempts."""
self.login_attempts += 1
def reset_login_attempts(self):
"""Reset login_attempts to 0."""
self.login_attempts = 0
class Admin(User):
"""A user with administrative privileges."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the admin."""
super().__init__(first_name, last_name, username, email, location)
# Initialize an empty set of privileges.
self.privileges = Privileges([])
class Privileges():
"""Stores privileges associated with an Admin account."""
def __init__(self, privileges):
"""Initialize the privileges object."""
self.privilege = privileges
def show_privileges(self):
"""Display the privileges this administrator has."""
for privilege in self.privileges:
print("- " + privilege)
3.2 my_user.py
from user import Admin
eric = Admin('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska')
eric.describe_user()
eric_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
eric.privileges.privileges = eric_privileges
print("\nThe admin " + eric.username + " has these privileges: ")
eric.privileges.show_privileges()
3.3 Output
Eric Matthes
Username: e_matthes
Email: e_matthes@example.com
Location: Alaska
The admin e_matthes has these privileges:
- can reset passwords
- can moderate discussions
- can suspend accounts
4 结语
第46篇
重温Python,希望能学点有意思的东西
排解自己工作上的不顺
个人水平有限,有问题欢迎各位大神批评指正!