Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to create a list of new objects in python

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading