0

Let's say I have code that looks like this:

class Test():
    def __init__(self, my_list=[]):
        self.my_list = my_list
    def add_stuff(self, nums):
        self.my_list.extend(nums)


x = Test()
x.add_stuff([1,2,3])
x.add_stuff([5,4,2,1])

Doing the append to the list in the case of the second x results in appending [1,2,3],[5,4,2,1] into the self.answers list. If I want a result where x.my_list=[1,2,3] and x.my_list=[5,4,2,1], what needs to be done? I still want to return/access the object and its data outside of the class but only contain the values that got passed in upon that method call.

user2899444
  • 313
  • 1
  • 3
  • 15
  • 1
    Your code has *numerous problems*. I picked one (using a default argument value that is mutable). Use `list.extend()` to extend a list with multiple values. – Martijn Pieters Mar 05 '15 at 08:33
  • Your `addStuff()` method should not return a new instance of `Test()`. Use `x = Test()` then on a separate line use `x.addStuff()`. – Martijn Pieters Mar 05 '15 at 08:33

0 Answers0