简体   繁体   English

访问类中的属性

[英]Accessing Attributes in a class

I'm a newbie to coding trying to understand OOP concepts.我是尝试理解 OOP 概念的编码新手。 Recently I came across a code and struggled to understand some lines最近我遇到了一个代码并且努力理解一些行

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

The following line seems very confusing.下面这行看起来很混乱。 If you can suggest a better way to code this I welcome your feedback如果您能提出更好的编码方式,我欢迎您的反馈

  eric.privileges.privileges = eric_privileges

I really appreciate your thoughts on this.我非常感谢您对此的想法。 Thanks a lot非常感谢

Regarding the line eric.privileges.privileges = eric_privileges ...关于行eric.privileges.privileges = eric_privileges ...

It seems indeed confusing to have a class Privileges with a single class variable named privileges .拥有一个名为privileges类变量的类Privileges确实令人困惑。 This may be a hint that the class is not really required.这可能暗示该类并不是真正必需的。 Then one possibility would be:那么一种可能性是:

1. Remove the class Privileges 1. 移除类Privileges

If the privileges are Admin-specific - ie assuming the privilege functionality is not used again in other parts of the code - why not use a list for storing all privileges?如果权限是特定于管理员的 - 即假设在代码的其他部分不再使用权限功能 - 为什么不使用列表来存储所有权限? The show_privileges() method could either be moved to the Admin class or be an independent function. show_privileges()方法可以移动到Admin类,也可以是一个独立的函数。 The second option - and the moderate use of classes in general - often leads to code that is easier to maintain and to test.第二种选择 - 以及一般适度使用类 - 通常会导致代码更易于维护和测试。

class Admin(User):    
    def __init__(self, first_name, last_name, username, email, location):
        super().__init__(first_name, last_name, username, email, location)
        self.privileges = []

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


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

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

Perhaps it does make sense to store the privileges in a separate class (eg it is supposed to store further variables and provide more functionality).也许将特权存储在单独的类中确实有意义(例如,它应该存储更多变量并提供更多功能)。 In this case, the current name may not be the best option to represent the class.在这种情况下,当前名称可能不是代表类的最佳选择。 So another possibility is:所以另一种可能是:

2. Rename the class Privileges 2.重命名类Privileges

If the class Privileges is required, perhaps renaming it would help to clarify things.如果需要类Privileges ,也许重命名它会有助于澄清事情。 Eg, calling it PrivilegeHandler (or what else is appropriate in the context) would lead to:例如,将其称为PrivilegeHandler (或上下文中其他合适的名称)将导致:

class Admin(User):    
    def __init__(self, first_name, last_name, username, email, location):
        super().__init__(first_name, last_name, username, email, location)
        self.privilege_handler = PrivilegeHandler()

class PrivilegeHandler:

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

    def add_privileges(self, new_privileges):
        self.privileges.extend(new_privileges)

    def show_privileges(self):
        print("\nPrivileges:")
        # ...

# ...
eric.privilege_handler.add_privileges(eric_privileges)
eric.privilege_handler.show_privileges()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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