Python Programming: from introduction to practice Chapter 9 class exercises -- class User

0 Preface

Python Programming: from introduction to practice Chapter 9 class exercises - class User

1 description of exercises

Exercise 9-3 users

Create a class named User that contains the property first_name and last_name, and several other attributes that are usually stored in the User profile. Define a User class named describe_ Method of User (), which prints the summary of User information; Define another one named greet_ Method of User (), which sends personalized greetings to users.
Create multiple instances representing different users and call the above two methods for each instance.

Exercise 9-5 login attempts

In the User class you wrote to complete exercise 9-3, add a name called login_ Attributes of attempts. Write a program called increment_ login_ Method of attempts (), which takes the attribute login_ Add 1 to the value of attempts. Write another one called reset_ login_ Method of attempts (), which takes the attribute login_ The value of attempts is reset to 0.
Create an instance according to the User class, and then call the method increment_login_attempts() more than once. Print attribute login_ The value of attempts to confirm that it is incremented correctly; Then, call the method reset_. login_attempts() and print the attribute login again_ The value of attempts and confirm that it is reset to 0.

Exercise 9-7 administrator

Administrator is a special kind of User. Write a class called Admin that inherits the User class you wrote to complete exercises 9-3 or 9-5. Add an attribute named privileges to store a list of strings (such as "can add post", "can delete post", "can ban user", etc.). Write a program called show_privileges(), which displays the privileges of the administrator. Create an Admin instance and call this method.

Exercise 9-8 permissions

Write a class called privileges, which has only one attribute - privileges, which stores the list of strings described in exercise 9-7. Show method_ Move privileges () into this class. In the Admin class, use an instance of privileges as its property. Create an Admin instance and use the method show_privileges() to display its permissions.

Exercise 9-11 importing the Admin class

Based on the work done to complete exercises 9-8. Store the User, privileges and Admin classes in a module, create a file, create an Admin instance in it, and call the show method on it_ Privileges() to make sure everything works correctly.

2. Self programming


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()


from user import User, Admin

user1 = User("A", "B", 'Abb', 5)

user2 = User("C", "D", 'Cdd', 0)

admin1 = Admin("E", "F", 'EfF', 10)
admin1.privileges.privileges = ['can add post', 'can delete post']

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 exercise 9-11 importing Admin class reference answer


"""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 = 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: " +
        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)


from user import Admin

eric = Admin('eric', 'matthes', 'e_matthes', '', 'alaska')

eric_privileges = [
    'can reset passwords',
    'can moderate discussions',
    'can suspend accounts',
eric.privileges.privileges = eric_privileges

print("\nThe admin " + eric.username + " has these privileges: ")

3.3 Output

Eric Matthes
  Username: e_matthes
  Location: Alaska

The admin e_matthes has these privileges: 
- can reset passwords
- can moderate discussions
- can suspend accounts

3 conclusion

Chapter 46

Review Python and hope to learn something interesting
Solve the problems in your work

Personal level is limited. If you have any problems, you are welcome to criticize and correct!

Tags: Python

Posted on Thu, 07 Oct 2021 15:19:13 -0400 by bluesoul