0

I have a class that contains a list of elements, each instance of a class contains a different type of element in the list (mainly floats and strings), the structure resembles the code below:

class series:
    ...
    data = []
    ...

When I create a number of this classes it seems that they point to the same address in memory, so when I append data to the list of one of the objects, all the objects have the same items in their respective lists and this behaviour could result problematic.

The workaround that I found in this article is to use the copy Object during the initialization of my series Object (see code below).

class series:
    ...
    data = []
    ...
    
    def __init__(self):
            ...
            self.data = copy.copy(self.data)

Is there a more elegant solution?

VLuca
  • 1
  • 1
  • 1
    `series.data` is a class attribute, it’s specific to the class so as you’ve noted there is only one of it, and so not sure why you’re surprised that there isn’t a possibility for `series.data` to have anything other than one location in memory. In `def __init__(self)` use `self.data = []` that will do the trick, i.e. don’t create/use the class attribute `data`. – DisappointedByUnaccountableMod Aug 11 '21 at 17:18
  • [This](https://stackoverflow.com/questions/207000/what-is-the-difference-between-class-and-instance-attributes) may help explain the difference. – sj95126 Aug 11 '21 at 17:18

0 Answers0