Python 列表对象属性“追加”是只读的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33355678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:13:36  来源:igfitidea点击:

Python List object attribute 'append' is read-only

python

提问by Kraegan Epsilon

as the title says, in python, I'm trying to make it so when someone types in a choice (in this case Choice13) then it deletes the old password from the list passwords and adds the new one instead.

正如标题所说,在python中,我试图做到这一点,当有人输入一个选项(在本例中为Choice13)时,它会从列表密码中删除旧密码并添加新密码。

passwords = ['mrjoebblock' , 'mrjoefblock' , 'mrjoegblock', 'mrmjoeadmin' ]
if choice == '3':
    password = raw_input('Welcome admin! I\'m going to need your password ')
        if password == 'mrjoeadmin':
            print('Welcome Mr. Joe!')
            Choice11 = raw_input('What would you like to do? Press 1 for changing your admin password, 2 for viewing a class\'s comments, or 3 for changing a class\'s password')
            if Choice11 == '1':
                print('You have chosen to change your password! ')
                Choice12 = raw_input('You will need to put in your current password to access this feature ')
                if Choice12 == 'mrmajoeadmin':
                    Choice13 = raw_input('What would you like to change your password to? ')
                    passwords.remove('mrjoeadmin')
                    passwords.append = Choice13

采纳答案by mgilson

To append something to a list, you need to callthe appendmethod:

要将某些内容附加到列表中,您需要调用append方法:

passwords.append(Choice13)

As you've seen, assigningto the append method results in an exception as you shouldn't be replacing methods on builtin objects -- (If you want to modify a builtin type, the supported way to do that is via subclassing).

如您所见,分配给 append 方法会导致异常,因为您不应该替换内置对象上的方法——(如果您想修改内置类型,支持的方法是通过子类化)。

回答by eyalsn

or you could modify the same list slot by doing:

或者您可以通过执行以下操作来修改相同的列表插槽:

passwords[passwords.index('mrjoeadmin')] = Choice13