Question

I'm trying to make a list of objects with different content but when I create the instance, it edits all other instances.

class Example(object):
    name = ''

   @classmethod
   def __init__(cls, name):
       cls.name = name

col = []
col.append(Example('text1'))
col.append(Example('text2'))
for item in col:
    print item.name

And it prints

'text2'
'text2'

When I expect it to print

'text1'
'text2'

I've also tried with

var = Example('text1')
col.append(var)

And I can't set different variable names because I want it to create instances in a loop.

Was it helpful?

Solution

Don't make __init__ a class method; it a instance initializer:

class Example(object):
    name = ''

   def __init__(self, name):
       self.name = name

By making it a class method, you made it alter the class, not the new instance created.

Without the @classmethod decorator, the class-level name attribute is entirely optional, you can remove it for most uses.

OTHER TIPS

You want this:

class Example(object):
   def __init__(self, name):
       self.name = name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top