2011-06-06 59 views
0

我正在尋找一種方法來設置字符串的值,而不改變字符串的類型。設置字符串的值而不將其設置爲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 

這樣的配置設置使用作爲一個字符串,但它仍然包含額外的信息,如果需要的話。

+1

Python變量不是C/C++意義上的變量。 – JBernardo 2011-06-06 22:46:04

回答

1

問題(你已經想通了)是t被分配給一個str類型的新對象,它沒有myattr。

我認爲這樣做是簡單地創建一個不從STR繼承一個類最簡單的方法,但包含字符串成員,也是「myattr」

+0

我想我真正希望的是,str類包含一個內部函數來更改值或保存其值的變量(我希望__值__或某物) – python5000 2011-06-06 23:01:37

+1

如果您希望對象具有字符串值,然後定義'__str __()'和/或'__unicode __()'方法。 – 2011-06-06 23:14:34

+2

@ python5000 - 實際的底層字符緩衝區沒有公開,請參閱http://svn.pythonmac.org/python24/python24-fat/Include/unicodeobject.h如果你有興趣@Ignacio - 我想他想設置它沒有字符串值 – dfb 2011-06-06 23:24:49

2

聲明t = "whatever"沒有「變化t「包含的值」,而是將t重新綁定到不同的對象。如果你想改變t那麼你必須通過屬性改變它,或者通過分配屬性或調用一個方法。

+0

我準備使用一種方法來設置字符串的值。我只是不想做'newt.myattr = oldt.myattr'來移動每個變量值,因爲然後我必須更新函數來爲每個添加到類中的屬性執行此操作。我希望有更優雅的東西。 – python5000 2011-06-06 23:04:54

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 
+0

是的,這是如何開始。我完全是你描述的,但是現在我的人生目標是創造一個版本,你仍然可以打印並得到「耶!」即使我需要創建一個t.setValue(「whatever」)函數,仍然可以訪問.myattr。 – python5000 2011-06-06 23:12:57

+0

@ python5000你的意思是打印t並獲得'測試'?你爲什麼需要這樣做?設置t.string,t.myattr並根據需要進行擴展有什麼問題?您始終可以創建t.setValue('whatever'),以便它修改self.string並使myattr保持獨立。 – Jacinda 2011-06-06 23:27:48

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] 
相關問題