繁体   English   中英

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

[英]Calling on a method from another class in python

我试图用下面的代码做的是创建一个单独的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()

尝试运行时,我收到以下错误。 有任何想法吗?

Traceback(最近一次调用最后一次):

 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个

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

如果您还没有,请参阅super上标准文档

暂无
暂无

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

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