0

文字列の型を変更せずに文字列の値を設定する方法を探しています。

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

これにより、構成設定を文字列として使用できますが、必要に応じて追加情報が含まれます。

4

4 に答える 4

2

このステートメントt = "whatever"は「に含まれる値を変更するt」のではなくt、別のオブジェクトに再バインドします。変更したい場合はt、属性に代入するか、メソッドを呼び出して、代わりに属性を介して変更する必要があります。

于 2011-06-06T22:49:36.860 に答える
1

問題 (あなたが理解した) は、t が myattr を持たない str 型の新しいオブジェクトに割り当てられていることです。

これを行う最も簡単な方法は、str から継承しないが、文字列メンバーと「myattr」を含むクラスを単純に作成することだと思います

于 2011-06-06T22:48:55.230 に答える
0

タプルやリストを使用しないのはなぜですか?

>>> 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]
于 2011-06-07T00:07:31.827 に答える
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 から継承したい場合 (ただし、これは実際にはあまり Pythonic ではなく、問題も解決しません):

class testStr(str):
    def __init__(self, string, myattr = ""):
        super(testStr, self).__init__(string)
        self.myattr = myattr
于 2011-06-06T22:53:46.547 に答える