如何在不设置为字符串类型的情况下设置字符串的值?
我想找到一种方法,可以在不改变字符串类型的情况下设置字符串的值。
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"那样工作,但我不想手动把myattr的值复制过来,如果我在testStr类中放入更多变量的话。
编辑:这是我最终想到的解决方案。它满足了我所有的需求,虽然我希望能有更优雅的方式,但我对此还是很满意:
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
这样可以将配置设置用作字符串,但如果需要,它仍然包含额外的信息。
4 个回答
0
你可以考虑这个方法。看起来它能提供你想要的功能。
class testStr(object):
def __init__(self, string, myattr = ""):
self.string = string
self.myattr = myattr
运行你展示的那些测试案例。
>>> from testStr import testStr
>>> t = testStr('testing')
>>> t.string
'testing'
>>> t.myattr = 'Yay!'
>>> t.myattr
'Yay!'
>>> t.string = 'whatever'
>>> t.string
'whatever'
>>> t.myattr
'Yay!'
或者,如果你真的想从 str 这个类型继承(不过这样做其实不太符合 Python 的风格,而且也不能解决你的问题):
class testStr(str):
def __init__(self, string, myattr = ""):
super(testStr, self).__init__(string)
self.myattr = myattr
1
你已经明白了问题所在,就是变量 t 被赋值为一个新的字符串对象,但这个对象没有 myattr 这个属性。
我觉得最简单的解决办法就是创建一个新的类,这个类不需要从字符串(str)继承,但可以包含一个字符串成员和 myattr 属性。
2
这句话 t = "whatever"
并不是在“改变 t
里面的值”,而是把 t
重新指向了一个不同的东西。如果你想要真正改变 t
的内容,你需要通过它的属性来修改,或者是给属性赋值,或者是调用一个方法。