0

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]

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.