开发者

Set value of a string without setting it to str type?

开发者 https://www.devze.com 2023-03-11 08:04 出处:网络
I\'m looking for a way to set a string\'s value without changing the type of the string. class testStr(str):

I'm looking for a way to set a string's value without changing the type of the string.

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"

If possible I would like myattr to maintain it's value while the string is set to a new value. It doesn't need to work like t = "whatever" but I don't want to manually copy over the values of myattr and more if I put more variables into the testStr class.

EDIT: Here is the solution I ended up coming up with. It satisfies all of my needs, I was hoping for something a little more elegant but I'm happy with this none the less:

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

This allows a configuration setting to be used as a string, however it does still contain the additional information if it was needed.


The statement t = "whatever" doesn't "change the value contained by t", but rather it rebinds t to a different object. If you want to change t then you must mutate it instead via an attribute, either by assigning to an attribute or by calling a method.


The problem (which you've figured out) is that t is being assigned to a new object of type str, which doesn't have myattr.

I think the simplest way to do this would be to simply create a class that doesn't inherit from str, but contains a string member as well as 'myattr'


You might consider this approach. It seems to provide the functionality you're looking for.

class testStr(object):
    def __init__(self, string, myattr = ""):
        self.string = string
        self.myattr = myattr

Running the same test cases as you showed.

>>> 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!'

Or, if you really want to inherit from str (but this is really less pythonic and also doesn't solve your problem):

class testStr(str):
    def __init__(self, string, myattr = ""):
        super(testStr, self).__init__(string)
        self.myattr = myattr


Why aren't you using a tuple or list?

>>> s = [ ["the string", 15], ["second string", 12] ]
>>> print s
[['the string', 15], ['second string', 12]]

>>> s[0][1] = 8;
>>> print s
[['the string', 8], ['second string', 12]]

>>> print s[0]
['the string', 8]

>>> print s[1]
['second string', 12]
0

精彩评论

暂无评论...
验证码 换一张
取 消