简体   繁体   中英

Calling methods inside other methods in Python

I have the following problem using object oriented programming. Write a class called Password_manager. The class should have a list called old_passwords that holds all of the user's past passwords. The last item of the list is the user's current password. There should be a method called get_password that returns the current password and a method called set_password that sets the user's password. The set_password method should only change the password if the attempted password is different from all the user's past passwords. Finally, create a method called is_correct that receives a string and returns a boolean True or False depending on whether the string is equal to the current password or not

Firstly i created a list with 5 random passwords (old_passwords) outside my class program. Next i initialized my program with one parameter (old_password lists). Next in my first method (get_password) i returned the last element of the list. In the set method i randomly chose one password from my list. The problem is in the third method where i want to see if the current password is equal to the one generated. How can i call the other two methods in my method (is_correct)?

import random

old_password=['a','b','c','d''e','f']

class Password_manager:

  def __init__(self,old_password):
    self.old_password=old_password

  def get_password(self):
    return self.old_password(len(self.old_password)-1)

  def set_password(self):
    return random.choice(self.old_password)

  def get_string(self):
    string=input('Digit string')
    while True:
      current_password=get_password()
      new_password=set_password()
      if new_password==current_password:
        return True
        break
      else:
        return False

It gives me errors: set_password() and get_password() not defined

get_password() and set_password() are instance methods. Unlike in languages like Java where they would already be in-scope for anything inside the class, Python makes you explicitly call those methods on self (that is, the current instance of the class).

This should work:

current_password = self.get_password()
new_password = self.set_password()

您需要使用“ self.get_password()”和“ self.set_password()”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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