【问题标题】:Calling on a method from another class in python在python中调用另一个类的方法
【发布时间】:2017-07-16 15:11:50
【问题描述】:

我试图用下面的代码做的是创建一个单独的权限类,它有一个名为 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__ 接受 first_namelast_name 参数,但您也传递了 privileges
  • 所以我不应该传递特权?
  • 我回答了我自己的问题。感谢您的帮助!

标签: python inheritance methods


【解决方案1】:

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

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

【讨论】:

  • 是的,我对 super 的工作原理有点困惑,但删除的权限使我的代码按预期的方式工作。感谢您的帮助!
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多