我有一个构造函数采用字典的类。字典中的一个值是另一个字典。我将最后一个字典中的每个键设置为我班级的属性。
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
我该怎么做?
答案 0 :(得分:1)
试试这个:
def __setattr__(self,name,value):
self.__dict__[name] = value
self.__dict__['_MyType__d']['Options'][name] = value
重新定义MyType类的__setattr__。 我查了一下
print myType.Options['Minimum']
print myType.Minimum
正确打印13(两者)。
编辑:添加了参考http://docs.python.org/reference/datamodel.html#customizing-attribute-access
答案 1 :(得分:0)
试试
myType.Options ['Minimum'] = 13