我正在尋找一種方法來設置字符串的值,而不改變字符串的類型。設置字符串的值而不將其設置爲str類型?
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
這樣的配置設置使用作爲一個字符串,但它仍然包含額外的信息,如果需要的話。
Python變量不是C/C++意義上的變量。 – JBernardo 2011-06-06 22:46:04