0

I came across the following problem in Python:

I have a class called BasebookDataContainer which is mainly a collection of Dicts.

Within a method of that class, I call a new instance of BasebookDataContainer like this:

class BasebookDataContainer:  
    def generate_sub_basebook(self, columnlist):  
       ....  
       newinstance = BasebookDataContainer()

A lot of strange things happen:

  1. newinstance automatically is loaded with all the data of the "self" instance of the class BasebookDataContainer
  2. When I change the data of newinstance, it also changes the data of the "self" instance

Is this normal and is there a way to avoid it?

Thanks for your answers.

Carlos Mermingas
  • 3,822
  • 2
  • 21
  • 40
Emanolo78
  • 309
  • 5
  • 10
  • 1
    Hi Emmanuel. Can you post the code for the `BasebookDataContainer` class? At least all [static properties](https://stackoverflow.com/questions/68645/are-static-class-variables-possible) that you've defined in it and its `__init__` method. – Carlos Mermingas Nov 28 '18 at 12:37
  • Where do you attach the data members to the class? If you attach a mutable object (a dict for example) in the class definition, it will be shared by reference across instances. If you don’t want this behavior, attach the dict inside of the __init__ instead. – user4437749 Nov 28 '18 at 12:37
  • How is the `__init__` method defined? Is it decorated as a `@classmethod`? – toti08 Nov 28 '18 at 12:57

1 Answers1

0

Thank you to every body for the feed-backs.
Actually, I had made a mistake:
In the BasebookDataContainer Class, I had declared a data structure containing a list of fields (lists, dicts, strings, etc...), directly in the class definition itself. As a result, when there were several instances of objects of the same class, all those attributes were stored in the same memory address. It was a mistake of mine, since I have a C++ background.
The correct way to do it:
Do not declare the structure fields in the Class definition (leave the values at None) and allocate memory in the init() method of the class. It works perfectly now. Lesson learned.

Emanolo78
  • 309
  • 5
  • 10