简体   繁体   中英

Python 3 Confusion About Dot Notation Use

New programmer here, and I'm having some trouble understanding this specific case using dot notation in this exercise from Eric Matthes' Python Crash Course . The exercise is from chapter 9 (9-11 Imported Admin), which introduces object-oriented programming with classes. The exercise wants me to import a module that contains a collection of classes used to model users and then add certain privileges to the administrator user. Here is the module I'm importing:

"""A collection of classes for modeling users."""

class User():
"""Represents a simple user profile."""

def __init__(self, first_name, last_name, username, email, location):
    """Initialize attributes to decribe 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):
    """Print 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):
    """Print a personalized message to the user."""
    print("\nHello, " + 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 back to 0."""
    self.login_attempts = 0 

class Admin(User):
"""Represents an administrator, a specific type of User."""

def __init__(self, first_name, last_name, username, email, location):
    """
    Initialize attritbutes of parent class.
    Then intialize attributes specific to admin.
    """
    super().__init__(first_name, last_name, username, email, location)

    self.privileges = Privileges() #instance attribute? Slightly confused here.

class Privileges():
"""Class to store an admin's privileges."""

def __init__(self, privileges=[]):
    """Initialize attributes for privileges."""
    self.privileges = privileges

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

I understand how this module works for the most part, except where I have self.privileges = Privileges() . I think this is an attribute for the class Admin(User) , which is directed toward what's inside of the `Privileges()' class ? (sorry for improper word choice)

The second part of the exercise is where I import the module and create an instance of Admin and then add certain privileges:

"""Import class Admin(User)"""
from user import Admin

"""Create admin instance."""
bertrand = Admin('bertrand', 'russell', 'bruss,' 'brussell@trinity.edu','united kingdom') 
bertrand.describe_user() # Apply method from parent class User()

"""Add admin privileges."""
bertrand_privileges = ['can add post', 
                'can delete post', 
                'can delete user',
                ]

bertrand.privileges.privileges = bertrand_privileges #I don't understand this!

"""Concatenate and apply method to show added privileges."""
print("\nThe admin " + bertrand.username + 
    " has these privileges: ")
bertrand.privileges.show_privileges()

When considering the line bertrand.privileges.show_privileges() , am I correct in thinking that .privileges tells Python to look at the instance bertrand and find the privileges attribute so it can call the method show_privileges from the Privileges() class?

My main misunderstanding, however, is the line bertrand.privileges.privileges = bertrand_privileges . Why the second .privileges ? if this line is any similar to the bertrand.privileges.show_privileges() line, what is the second .privileges trying to refer to? When I delete the second .privileges and run the code, I get an error. So I think it must have some purpose. Any help would be appreciated. Perhaps I'm just misguided in my understanding of how this instance attribute thing works? Also, why would this type of approach be useful?

Your first assumption is correct.

What is happening in the second part of your question is pretty much the same. You are grabbing the instance attribute bertrand.priveleges, which is an instantiated version of the Privileges class. Since it was instantiated with no arguments, the keyword argument in the Privileges class init is used, or an empty list.

Now when you do bertrand.priveleges.priveleges, you would have an empty list, however since you set this variable to be "bertrand_priveleges", which is the list containing bertrand's privelages, now bertrand.priveleges.priveleges will refer to this populated list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM