Python 3关于点表示法的混淆使用

时间:2017-07-24 23:50:20

标签: python python-3.x oop attributes

这里的新程序员,在使用Eric Matthes的 Python Crash Course 的练习中使用点符号理解这个具体案例时遇到了一些麻烦。练习来自第9章(9-11 Imported Admin),它引入了面向对象的编程。练习要求我导入一个模块,该模块包含用于为用户建模的类集合,然后向管理员用户添加某些特权。这是我要导入的模块:

"""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.")

我理解这个模块大部分是如何工作的,除了self.privileges = Privileges()。我认为这是类Admin(User)的一个属性,它指向`Privileges()'类的内部? (对不正确的单词选择感到抱歉)

练习的第二部分是我导入模块并创建Admin实例然后添加某些权限的地方:

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

在考虑行bertrand.privileges.show_privileges()时,我认为.privileges告诉Python查看实例bertrand并找到privileges属性以便它可以调用来自show_privileges类的方法Privileges()

然而,我的主要误解是bertrand.privileges.privileges = bertrand_privileges行。 为什么第二个.privileges?如果此行与bertrand.privileges.show_privileges()行类似,那么第二个.privileges试图引用的是什么?当我删除第二个.privileges并运行代码时,出现错误。所以我认为它必须有一些目的。任何帮助,将不胜感激。也许我只是在理解这个实例属性是如何工作的时候被误导了?另外,为什么这种方法会有用?

1 个答案:

答案 0 :(得分:-1)

你的第一个假设是正确的。

问题的第二部分发生的情况几乎相同。您正在获取实例属性bertrand.priveleges,它是Privileges类的实例化版本。由于它是在没有参数的情况下实例化的,因此使用Privileges类init中的关键字参数或空列表。

现在当你做bertrand.priveleges.priveleges时,你会有一个空列表,但是因为你将这个变量设置为" bertrand_priveleges",这是包含bertrand的privelages的列表,现在bertrand.priveleges.priveleges将引用此填充列表。