文字列の型を変更せずに文字列の値を設定する方法を探しています。
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
これにより、構成設定を文字列として使用できますが、必要に応じて追加情報が含まれます。