2012-07-04 55 views
1

看一看下面的方法:的Python:沒有對象創建

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 

問題:Althoug文件中的每一行是不同的ad_mediums字典中的值都相同的值。對我來說,彷彿創建一個新對象「ad_medium = Objects.Ad_Medium()」沒有任何效果,只是簡單地覆蓋了前一個循環對象的值。

我該如何解決這個問題?

編輯:AD_MEDIUM類

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 
+0

你能發佈Ad_Medium類的相關部分?某些東西可能是課堂級別的(例如「類別」),而不是實例級別的。 – DSM

回答

5

在你的類定義,ID,類別和印象是類屬性(由所有實例共享)。語句ad_medium.id = int(parts[0])定義了一個'id'實例屬性,但類別和印象(不是反彈但是變異)的所有操作都對類屬性起作用。您希望您的類定義有,你創建的實例屬性的初始化方法,即:

class Ad_Medium(object): 
    def __init__(self): 
     self.id = 0 
     self.categories = { 1:0.0, 2:0.0, 3:0.0, 4:0.0, 5:0.0, 6:0.0, 7:0.0 } 
     self.impressions = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0 } 

我強烈建議你瞭解Python的對象模型,屬性查找規則等