how to create a list of new objects in python

Question:

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]

Asked By: Rufus

||

Answers:

_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.

Answered By: Carcigenicate

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)
Answered By: PCDSandwichMan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.