我正在寻找一种在不更改字符串类型的情况下设置字符串值的方法。
class testStr(str):
myattr = ""
# this works fine.
t = testStr("testing")
t.myattr = "Yay!"
print "String value is: '" + t + "' and its attr is set to '" + t.myattr + "'"
# obviously once this is done the type of t goes back to str
# and I lose the value of .myattr
t = "whatever"
如果可能的话,我希望 myattr 在字符串设置为新值时保持它的值。它不需要像 t = "whatever" 那样工作,但如果我将更多变量放入 testStr 类,我不想手动复制 myattr 的值等等。
编辑:这是我最终提出的解决方案。它满足了我的所有需求,我希望有一些更优雅的东西,但我对此仍然很满意:
class config:
class ConfigItem(str):
def __init__(self, value):
super( str, self ).__init__()
self.var1 = "defaultv1"
self.var2 = "defaultv2"
def __init__(self):
self.configTree = {}
def __getitem__(self, key):
if ( self.configTree.has_key(key) ):
return self.configTree[key]
return ""
def __setitem__(self, key, value):
if ( value.__class__.__name__ == "ConfigItem" ):
self.configTree[key] = value
return
if ( value.__class__.__name__ == "str" ):
item = None
if ( self.configTree.has_key(key) ):
item = self.configTree[key]
new_item = self.ConfigItem(value)
for attr in item.__dict__:
new_item.__setattr__(attr, item.__getattribute__(attr))
self.configTree[key] = new_item
else:
item = self.ConfigItem(value)
self.configTree[key] = item
# test it out
cfg = config()
cfg["test_config_item"] = "it didn't work."
cfg["test_config_item"].var1 = "it worked!"
cfg["test_config_item"] = "it worked!"
print cfg["test_config_item"]
print cfg["test_config_item"].var1
这允许将配置设置用作字符串,但如果需要,它仍然包含附加信息。