错误消息:当对象包含属性时,对象不包含属性

时间:2017-10-23 16:09:40

标签: python methods

我正在实施一个带有下载的“播放器”模块:

  • 验证功能
  • 具有用户名和密码属性的Player对象
  • 播放器的更改密码方法

运行以下change_password方法时,收到错误:

while(old_password!=self.password_str):
    AttributeError: 'Player' object has no attribute 'password_str'

然而,我将password_str定义为Player的属性。任何想法发生了什么?

class Player(object):

    def __init__(self, username_str="-", password_str=""):
        while (not validated(password_str)):
            self.password_str=input("Password is invalid. Please try again:")
            self.username=username_str

    def change_password(self,old_password):
        MAX_ATTEMPT=3
        num_of_fails=0
        while(old_password!=self.password_str):
            num_of_fails+=1
            if(num_of_fails<MAX_ATTEMPT):
                old_password=input("Thej passwword entered is invalid. Please try again. \
                (You have "+str(MAX_ATTEMPT-num_of_fails)+" attempts reamining)")
            else:
                print("Incorrect password entered too many times. Your account is temporarily locked.")
                break

        if(num_of_fails<MAX_ATTEMPT):
            new_password=input("please enter a new password.")

            while(not validated(new_password)):
                new_password=input("New password is invalid. Please try again")

            self.password_str=new_password
            print("Password has been successfully changed!")

2 个答案:

答案 0 :(得分:1)

如果密码有效,则while循环未执行且self.password_str未初始化。请尝试以下代码:

 def __init__(self, username_str="-", password_str=""):
    self.password_str = password_str
    while (not validated(self.password_str)):
        self.password_str=input("Password is invalid. Please try again:")
        self.username=`enter code here`

答案 1 :(得分:0)

如果传递给validated的密码的__init__返回True,则您的while循环内容将无法执行,因此password_strusername属性根本不会设置。