Python速成课程 - 第9章 - eric.privileges.show_privileges()

时间:2017-09-30 18:01:44

标签: 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_privileges。但是eric.privileges.privileges部分是什么?我认为eric.privileges是self.privileges。但是第二个。特权怎么样?

1 个答案:

答案 0 :(得分:0)

我有同样的书,但在第8章我自己。尽管有评论,我会尽力解释代码。

eric,是管理员object的{​​{1}},来自用户class。每个管理员都有一组权限,inherits包含class

此代码:

list

你调用eric.privileges 类中的权限(eric是管理员的admin),它是Admin类的一个属性。

此代码:

object

在第一个权限之后,正在访问权限.privileges 中的list,并为其分配了class

将第二次特权调用视为Admin中特权列表中特权列表的网关。这本书可能不想深入介绍,但作者可能已将它们声明为list的私有,并在Admin类中放置了一个setter。