2012-08-10 20 views
1

我使用vars()「即時創建」一些對象變量。這似乎不是最乾淨的操作。但是,除此之外,我還可以如何生成對象的屬性名稱,而無需手動定義它們(在這種情況下,字典相對較短,但這只是一些測試數據)。我知道here描述的這種做法帶來的問題。使用var()創建字典鍵的屬性名稱

class DerivedProf(Prof): 
    def __init__(self,profiel, TAG, code_DB): 
     Prof.__init__(self, profiel, TAG) 
     self.CountCodes(self.attr, code_DB) 

def CountCodes(self, attr, code_DB): 
    count = 0 
    for key, value in code_DB.iteritems(): 
     if value[0].lower() == 'true': 
      for i,p in enumerate(attr): 
       if int(attr[i].code2) == value[1]: 
        count += 1 
       else: 
        continue 
      vars(self)[key] = count 

code_DB = {'code_72': ['true',72], 
      'code_74': ['true',74], 
      'code_76': ['true',76], 
      'code_88': ['true',88]} 

回答

4

也許你正在尋找setattrgetattr。你可以做setattr(self, key, count)然後getattr(self, key)

+0

這正是我一直在尋找的!謝了哥們。 – LarsVegas 2012-08-10 09:05:24

相關問題