在python中调用另一个类的方法

时间:2017-02-25 20:55:10

标签: python inheritance methods

我正在尝试使用下面的代码创建一个单独的Privilege类,该类具有一个名为show_Privileges的方法。该方法打印用户权限。

class User:
    """Describes users of a system"""
    def __init__(self, first_name, last_name):
        """Initialize first name and last name"""
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = 0

    def describe_user(self):
        """Describing the user"""
        print("User " + self.first_name.title() + " " + self.last_name.title() + ".")

    def greet_user(self):
        """Greeting"""
        print("Hello " + self.first_name.title() + " " + self.last_name.title() + "!")

    def increment_login_attempts(self):
        """Increments the number of login attempts by 1"""
        self.login_attempts += 1
        print("User has logged in " + str(self.login_attempts) + " times.")

    def reset_login_attempts(self):
        self.login_attempts = 0
        print("User has logged in " + str(self.login_attempts) + " times.")

class Privileges:
    """Making a privileges class"""
    def __init(self, privileges):
        """Defining the privilege attribute"""
        self.privileges = privileges

    def show_privileges(self):
        """Defining privileges"""
        rights = ['can add post', 'can delete post', 'can ban user']
        print("The user has the following rights: \n")
        for right in rights:
            print(right.title())

class Admin(User):
    """Describes admin rights"""
    def __init__(self, first_name, last_name, privileges):
        """Initialize first and last name"""

        super().__init__(first_name, last_name, privileges)
        self.privileges = Privileges()




super_Admin = Admin('Ed', 'Ward', 'root')
print(super_Admin.describe_user())
super_Admin.privileges.show_privileges()

尝试运行时,出现以下错误。有什么想法吗?

追踪(最近一次呼叫最后一次):

 File "users.py", line 50, in <module>
    super_Admin = Admin('Ed', 'Ward', 'root')
  File "users.py", line 44, in __init__
    super().__init__(first_name, last_name, privileges)

TypeError: init ()需要3个位置参数,但是给出了4个

1 个答案:

答案 0 :(得分:0)

<{1}} __init__ User接受3个参数即self, first_name, last_name但你在这里传递4,privileges是额外的参数。

如果您还没有,请参阅standard docs on super