首页 > 解决方案 > 如何引用另一个类的实例化属性

问题描述

我想在不同的类中使用实例属性(在本例中为用户的名字“Juan”)以将其用作打印其所有权限的提示。

我所做的解决方案是在代码行中删除“self.first_name”。所以而不是

print("Since your an admin," + self.first_name + ", you have the following privileges: ")

现在变成了

print("Since your an admin, you have the following privileges: ")

这仍然可以,但没有它引用实例属性。

问题是我如何才能放弃在提示中包含“Juan”的最初想法?为了使用那行代码,我应该进行哪些更改?

# Snippet of the Code
class Privileges:
    """Make a Privilege Object for each specific user"""
    def __init__(self):
        """Initialize the privileges attributes"""
        self.privileges = ["can delete posts", "can ban user", "can add post"]

    def show_privileges(self):
        """Print all the privileges of the admin"""
        print("Since your an admin," + self.first_name + ", you have the following privileges: ")
        for privilege in self.privileges:
            print("You " + privilege + ".")


class Admin(User):
    """Make an Admin User and Inherit attributes from class "User" """
    def __init__(self, first_name,  last_name, age, gender):
        super().__init__(first_name, last_name, age, gender)
        self.privileges = Privileges()


user_1 = Admin("juan", "dela cruz", 5, "male")
user_1.privileges.show_privileges()

==================================================== ====================== 预期的输出是:

Since your an admin, Juan, You have the following privileges: 
You can delete posts.
You can ban user.
You can add post.

错误信息:

    print("Since your an admin," + self.first_name + ", you have the following privileges: ")
    AttributeError: 'Privileges' object has no attribute 'first_name'

标签: python-3.xclassattributesinstance

解决方案


无法直接添加父对象的名称,因为可能存在对同一特权的多个引用。您需要将用户名传递给 Privilege 实例。

您可以在构造函数中执行此操作,这会将权限绑定到单个用户。另一种方法是将名称传递给show_privileges. 这是更通用的方法,尽管它确实需要更多的输入,因为您每次都必须通过它。


推荐阅读