Home > Software design >  how to create a list of new objects in python
how to create a list of new objects in python

Time:11-05

I am trying to create a list of new objects in python (as in separate memory locations, not references)

class example:
    _name = ""
    _words = []
    def __init__(self,name):
        _name = name

    def add_words(self,new_words):
        for i in new_words:
            self._words.append(i)

examples = [example("example_1"),example("example_2"),example("example_3")]
examples[0].add_words(["test1","test2"])

print(examples[2]._words)

print(examples[2]._words) outputs ["test1","test2"] I expected [] as I only added words to examples[0]

CodePudding user response:

_words = [] at the top of the class makes _words a class variable, not an instance one. All classes instances share _words with how you have it now.

Make it an instance variable instead:

class example:
    def __init__(self,name):
        self._words = []

    . . .

You'll likely want to fix _name as well.

CodePudding user response:

Hope this helps:

class example:
    def __init__(self, name):
        self._words = []
        self._name = name

    def add_words(self, new_words):
        for i in new_words:
            self._words.append(i)


examples = [example("example_1"), example("example_2"), example("example_3")]
examples[0].add_words(["test1", "test2"])

print(examples[2]._words)
  • Related