Have a look at the following method:
def load_ad_mediums_from_file(self, filename ):
file = io.open( filename, "r" )
ad_mediums = {}
for line in file:
if len(line) > 0 and line[0] != 'a':
parts = line.strip().split(";")
ad_medium = Objects.Ad_Medium()
ad_medium.id = int( parts[0] )
for i in range(1,8):
cat_parts = parts[i].strip().split(",")
category_id = int(cat_parts[0]);
ad_medium.categories[category_id] = float(cat_parts[1])
ad_medium.impressions[category_id] = int(cat_parts[2])
ad_mediums.update( { ad_medium.id : ad_medium } )
file.close()
return ad_mediums
The problem: Althoug each line in the file is different the values in the ad_mediums dictionary have all the same values. To me it looks like as if the creation of a new object “ad_medium = Objects.Ad_Medium()” has no effect but just simply overwrites the values from the object of the previous loop.
How can I fix this?
EDIT: The Ad_Medium class
class Ad_Medium(object):
id = 0
categories = { 1:0.0, 2:0.0, 3:0.0, 4:0.0, 5:0.0, 6:0.0, 7:0.0 }
impressions = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0 }
def __str__(self):
string = str(self.id) + ";"
for i in range(1,8):
string += str(i) + "," + str( self.categories[i] ) + "," + str( self.impressions[i] ) + ";"
return string[:-1] + "\n"
def normalize_categories_with_impressions(self ):
impressions = 0.0
for i in range(1,8):
impressions += float(self.impressions[i])
if impressions == 0.0:
return
for i in range(1,8):
self.categories[i] = float(self.categories[i])/float(impressions)
def reset_categories(self):
for i in range(1,8):
self.categories[i] = 0
In your class definition, id, categories and impressions are class attributes (shared by all instance). The
ad_medium.id = int( parts[0] )statement defines an ‘id’ instance attribute, but all the operations on categories and impressions (which are not rebound but mutated) work on the class attributes. You want your class definition to have an initializer method where you create the instance attributes, ie :I strongly suggest that you learn more about Python’s object model, attribute lookup rules etc.