2012-02-08 36 views
1

我有一個類,構造函數需要一個字典。字典中的一個值是另一個字典。我將這個最後一個字典中的每個鍵都設置爲我的班級的一個屬性。通過屬性更改內部字典的值

class MyType(object): 
    def __init__(self, d): 
      self.__d = d 
      for k,v in self.__d['Options'].items(): 
       setattr(self, k, v) 
    def __GetName(self): 
     return self.__d['Name'] 
    Name = property(__GetName, None, None, "The name of my type") 
    def __GetOptions(self): 
     return self.__d['Options'] 
    Options = property(__GetOptions, None, None, "The options of my type") 

myType = MyType({'Name': "Summary", 'Options': {'Minimum': 5, 'Treshold': 7}}) 

我希望能夠通過屬性具有相同的名稱更改選項字典中的值:

myType.Minimum = 13 

print myType.Options['Minimum'] # returns 5, I would like to see here 13 

我該怎麼辦呢?

回答

1

嘗試這種情況:

def __setattr__(self,name,value): 
    self.__dict__[name] = value 
    self.__dict__['_MyType__d']['Options'][name] = value 

redefyning類的MyType的__setattr__。 我檢查了

print myType.Options['Minimum'] 
print myType.Minimum 

正確打印13(都)。

編輯:添加引用http://docs.python.org/reference/datamodel.html#customizing-attribute-access

+0

追加這個方法其他的人看起來更無害後... – jimifiki 2012-02-08 13:30:21

0

只要嘗試

myType.Options [ '最小'] = 13