Simple update class instance

I would like to create a very simple class in Python such that, starting from an initial list of elements [3,7,2,7,81], an other list of numbers can be added, in this case a single element 40. Here is my solution:

class Add_elements:

    def add(self, elements):
        list = [self.list,elements]
        return list

add_elements = Add_elements()
add_elements.add([3,7,2,7,81])
add_elements.add([40])

This should return something like:

[[3,7,2,7,81],40]

The issue with this is that the list of elements is reset every time, there is no memory of the previous elements added. Any solution?

1 answer

  • answered 2019-07-18 15:48 Sweeper

    You probably need an initialiser to initialise self.list:

    class Add_elements:
        def __init__(self):
            self.list = None
    
        def add(self, elements):
            if self.list is None:
                self.list = elements
            else:
                self.list = [self.list,elements]
            return self.list
    

    This will make list an attribute of Add_elements - part of its state. And when you call add, it changes that state.

    EDIT:

    If you want to remove the square brackets when calling add, you can do something like this:

    def add(self, *elements):
        if self.list is None:
            self.list = list(elements)
        else:
            self.list = [self.list,list(elements)]
        return self.list