I have a simple class with a string and a dictionary. When I make multiple objects of the class, apparently the dictionary does not get initialized properly. Dictionaries of all objects contains the entry for last object created. The code is:
# a simple class with a string and a dictionary:
class Myclass:
name = ""
valuedict = {}
# a list for objects:
mylist = []
# create 3 objects:
for i in range(3):
mc = Myclass()
mc.name = str(i)
mc.valuedict['name'] = str(i)
mylist.append(mc)
# disply objects in list:
for item in mylist:
print("-----------------")
print("name = ", item.name)
print("name in dict = ", item.valuedict['name'])
The output is:
-----------------
name = 0
name in dict = 2
-----------------
name = 1
name in dict = 2
-----------------
name = 2
name in dict = 2
The name strings are 0, 1 and 2 as expected but name in dictionary is 2 in all 3 objects. Where is the problem and how can it be solved? Thanks for your help.