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()
This should return something like:
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?
You probably need an initialiser to initialise
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
listan attribute of
Add_elements- part of its state. And when you call
add, it changes that state.
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