Python速成班第9章eric.privileges.show\特权()

2024-05-14 22:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习Python速成课程,学习第9章,课程。我正在解决其中一个问题,并去图书网站获得解决方案。除了一行代码外,我了解它的大部分工作原理。以下是全部代码:

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():
    """A class to store an admin's privileges."""

    def __init__(self, privileges=[]):
        self.privileges = privileges

    def show_privileges(self):
        print("\nPrivileges:")
        if self.privileges:
            for privilege in self.privileges:
                print("- " + privilege)
        else:
            print("- This user has no privileges.")


eric = Admin('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska')
eric.describe_user()

eric.privileges.show_privileges()

print("\nAdding privileges...")
eric_privileges = [
    'can reset passwords',
    'can moderate discussions',
    'can suspend accounts',
    ]
eric.privileges.privileges = eric_privileges
eric.privileges.show_privileges()

我不清楚的是eric.privileges.privileges = eric_privileges行。我知道它指向的是包含列表的eric\u特权。但问题是什么埃里克。特权。特权部分?我想埃里克。特权是自我保护特权. 但是第二个呢?特权?你知道吗


Tags: nameselfemaildefusernameloginlocationfirst
1条回答
网友
1楼 · 发布于 2024-05-14 22:26:58

我也有这本书,不过是关于第八章的。尽管有评论,我还是会尽力解释代码的。你知道吗

eric,是管理员classobject,它inherits来自用户。每个管理员都有一组特权,即包含listclass。你知道吗

此代码:

eric.privileges

调用位于admin类中的privileges(eric毕竟是Admin的object),它是Admin类的一个属性。你知道吗

此代码:

.privileges

在第一个特权之后,正在访问特权class中的list,他被分配了一个list。你知道吗

将对privileges的第二次调用看作是从Admin访问privileges类中的privileges列表的网关。这本书可能不想更深入地讨论,但作者可以用_将它们声明为private,并在Admin类中放置一个setter。你知道吗

相关问题 更多 >

    热门问题