How to fix? TypeError: argument of type 'PasswordManager' is not iterable

Question:

I keep getting the following error and I can’t seem to find a solution for it.

    if password not in old_passwords:
TypeError: argument of type 'PasswordManager' is not iterable

For clarity, I needed to create a class called ‘PasswordManager’. The class should have a list called ‘old_passwords’. The list contains all past passwords, the last index of the list should be the current password. The required methods are ‘set_password’, ‘get_password’ and ‘is_correct’.

‘get_password’ should return the current password.

‘set_password’ sets a new password. It should only change the password if the attempted password is different from all the user’s past passwords.

‘is_correct’ receives a string and returns a boolean True or False depending on whether the string is equal to the current password or not.

class PasswordManager():
    old_passwords = []
    def get_password(old_passwords):
        return old_passwords[len(old_passwords-1)]

    def set_password(old_passwords, password):
        if password not in old_passwords:
            old_passwords.append(password)

    def is_correct(old_passwords, password):
        if password == old_passwords[len(old_passwords-1)]:
            return True
        else:
            return False

Does anyone have an idea that could help me? Thanks in advance!

Asked By: jb18

||

Answers:

python class methods require first argument as class itself. moreover, you cannot directly access class variables or methods in its methods.
need to use something like self.somemethod() or self.somevariable

class PasswordManager():
    old_passwords = []
    def get_password(self):
        return self.old_passwords[-1]

    def set_password(self, password):
        if password not in self.old_passwords:
            self.old_passwords.append(password)

    def is_correct(self, password):
        if password == self.old_passwords[-1]:
            return True
        else:
            return False

also, you are accessing last item in list wrong way.
old_passwords[len(old_passwords-1)] should be old_passwords[len(old_passwords)-1].
but, old_passwords[-1] is better choice.

Answered By: Abhi747

I think you need to review how to use classes in python.
Your class needs a constructor, where you can instantiate your class attributes (in your case old_passwords) and you can access them with self.
An example of your use case could be

class PasswordManager():
  
  def __init__(self):
    self.old_passwords = []

  def get_password(self):
    return self.old_passwords[-1]

  def set_password(self, password):
    if password not in self.old_passwords:
        self.old_passwords.append(password)

  def is_correct(self, password):
    return password == self.old_passwords[-1]

With [-1] you can access the last element of a list.
__init__ is the constructor method in python.

Answered By: Gianluca Viganò