Список __init__ сохраняет изменения после удаления

У меня возникла проблема, когда кажется, что информация в списке не «сбрасывается» до значений по умолчанию, хотя я считаю, что это должно быть. Пожалуйста, помогите мне понять, что происходит

У меня есть 2 файла, первый содержит следующий код.

Файл:testing.py

import sys
import getopt
import time

import testing2

entry = ["one","two"]
for input in entry:
    obj = testing2.thing(input)
    print ("{0}:\n  Input:{1}\n  Other:{2}").format(1,obj.needed_input,obj.other_thing)
    obj.change()
    print ("{0}:\n  Input:{1}\n  Other:{2}").format(2,obj.needed_input,obj.other_thing)
print ("\n")

for input in entry:
    obj = testing2.expectedthing(input)
    print ("{0}:\n  Input:{1}\n  Other:{2}").format(1,obj.needed_input,obj.other_thing)
    obj.change()
    print ("{0}:\n  Input:{1}\n  Other:{2}").format(2,obj.needed_input,obj.other_thing)

print("\n")
for input in entry:
    obj = testing2.actualthing(input)
    print ("{0}:\n  Input:{1}\n  Other:{2}").format(1,obj.needed_input,obj.other_thing)
    obj.change()
    print ("{0}:\n  Input:{1}\n  Other:{2}").format(2,obj.needed_input,obj.other_thing)

sys.exit(1)

И второй файл выглядит следующим образом:

Файл: testing2.py

def error_die(errstring):
    print('A Fatal Error has occurred: "{0}"').format(errstring)
    sys.exit(0)

class thing:
    def __init__(self,needed_input,other_thing="something"):
        if needed_input == None:
            error_die('invalid input')
        self.needed_input=needed_input
        self.other_thing=other_thing
    def change(self):
        self.other_thing="something else"
#

class expectedthing:
    def __init__(self,needed_input,other_thing=["one thing","two thing"]):
        if needed_input == None:
            error_die('invalid input')
        self.needed_input=needed_input
        self.other_thing=other_thing
    def change(self):
        self.other_thing=["one thing","three thing"]
#

class actualthing:
    def __init__(self,needed_input,other_thing=["one thing","two thing"]):
        if needed_input == None:
            error_die('invalid input')
        self.needed_input=needed_input
        self.other_thing=other_thing
    def change(self):
        self.other_thing.append("three thing")
        self.other_thing.remove("two thing")
#

И чего я не получаю, так это того, что я ожидал бы, что функции «actualthing» и «expectedthing» дадут одинаковые результаты, однако это не так.

Вот что я получаю в результате

>python testing.py

1:
  Input:one
  Other:something
2:
  Input:one
  Other:something else
1:
  Input:two
  Other:something
2:
  Input:two
  Other:something else


1:
  Input:one
  Other:['one thing', 'two thing']
2:
  Input:one
  Other:['one thing', 'three thing']
1:
  Input:two
  Other:['one thing', 'two thing']
2:
  Input:two
  Other:['one thing', 'three thing']


1:
  Input:one
  Other:['one thing', 'two thing']
2:
  Input:one
  Other:['one thing', 'three thing']
1:
  Input:two
  Other:['one thing', 'three thing']
Traceback (most recent call last):
  File "testing.py", line 45, in <module>
    obj.change()
  File "Z:\scripts\testing2.py", line 25, in change
    self.other_thing.remove("two thing")
ValueError: list.remove(x): x not in list

Ясно, что это не тот код, который я использую, однако он дает тот же результат. Из-за того, как я написал этот скрипт, «other_thing» может измениться в зависимости от параметров и аргументов, предоставленных пользователем во время выполнения скрипта, поэтому я не могу просто сказать, чтобы он был равен этому. Это список, потому что мне нужно иметь возможность изменять длину от 1 до 40 элементов (еще раз на основе пользовательского ввода). Любая идея о том, как я должен справиться с этим?

Спасибо за помощь, все пригодится.


person Linx    schedule 21.02.2014    source источник
comment
Кроме того, self.needed_input=needed_input и self.other_thing=other_thing не копируют список.   -  person thefourtheye    schedule 21.02.2014
comment
Также, пожалуйста, взгляните на этот ответ, чтобы узнать, что на самом деле происходит и как это исправить.   -  person thefourtheye    schedule 21.02.2014
comment
Две вещи: 1) мы должны скопировать список только так, как я показал в ответе, на который я дал ссылку в комментарии. 2) Не оставляйте в параметрах изменяемые объекты, проверьте дублирующий вопрос.   -  person thefourtheye    schedule 21.02.2014
comment
@thefourtheye Большое спасибо, я не видел этого, когда искал. Спасибо.   -  person Linx    schedule 21.02.2014