2013-03-20 34 views
0

接下來,在我學習Python的過程中,我遇到了一個問題。一個變量是否可以在一個程序中創建,通過連接字符串命名,並用於存儲一個對象?在程序中創建變量

所以,我的對象:

class Veg: 
    def __init__(self, x): 
     self.name = x 
     print('You have created a new vegetable:', self.name, end='\n') 

現在,創建一個變量:

tag = 1 
newVegObj = 'veg' + str(tag) #Should create a variable named 'veg1' 
newVegObj = Veg('Pepper') #Creates an object stored in 'newVegObj' :(

但我想創建的對象存儲在 'veg1'。然後,我可以這樣做:

tag = tag + 1 
newVegObj = 'veg + str(tag) #Create a variable named 'veg2' 
newVegObj = Veg('Tomato') 

的目標是veg1.name =辣椒和veg2.name =番茄,並能夠不斷創造額外的變量來存儲更多的蔬菜。

我不知道這是否可行。如果是這樣,並且如果這需要複雜的解決方案,請您提供一個有用的代碼解釋說明嗎?希望它的東西很簡單,我只是沒有想過。

在此先感謝!你們是最棒的!

+0

不,你錯了。你不想那樣。你也許想要一個字典。或者一個列表。 – geoffspear 2013-03-20 14:42:05

+0

你剛剛刪除了一個對象。你創建了一個veg,然後當你將它存儲到newVegObj時,你擺脫了舊的引用... – 2013-03-20 14:43:01

+0

也許如果你告訴我們你真的想做什麼,那麼可以幫助;它似乎是你實際上試圖通過一個晦澀的功能來實現... – akaIDIOT 2013-03-20 14:44:50

回答

0

考慮到您的意見,類似以下內容可能會有用。

names = ['Tomato', 'Snoskommer', 'Pepper'] # a list containing 3 names 
vegetables = {} # an empty dictionary 

for name in names: # just textual: for each name in the names list ... 
    new_veg = Veg(name) # create a new vegetable with the name stored in the variable 'name' 
    vegetables[name] = new_veg # add the new vegetable to the vegetable dictionary 

# at this point, the vegetables dictionary will contain a number of vegetables, which you can find by 
# 'indexing' the dictionary with their name: 
print(vegetables['Tomato'].name) # will print 'Tomato' 

希望幫助到在已瞭解一些Python基礎,雖然在開始一個簡單的教程可能是最好的:)


要延長,可以作出類似以下後來改變的事情:

高清add_vegetable(名稱): 如果名稱中的蔬菜: 打印( '已存在使用該名稱的蔬菜......') 其他: 蔬菜[名] = Ve的克(名稱)

調用函數的蔬菜添加到列表:

add_vegetable('Cucumber') 

後該字典將包含一個名爲「黃瓜」另一蔬菜。

但是,再次:通過一些介紹教程,http://python.org應該能夠指出你一些。

+0

這確實有幫助!謝謝! :)顯然我是在錯誤的軌道上。我一直試圖從三本不同的書中學習這些東西,而且我沒有編程經驗。所以從你的回答中,爲了添加一種新的蔬菜,我只需要把那個素食補充到列表中。從那裏它被創建爲一個對象並添加到字典中? – Gregory6106 2013-03-20 15:19:10

+0

不自動; 「for」循環是將新蔬菜添加到列表中的東西。請注意,上面的代碼是* only *來演示一些關於列表和字典的內容,這些代碼段在功能上相當無用。例如,要添加一個新的蔬菜到列表中,您可以使用一個函數。 – akaIDIOT 2013-03-20 15:22:01

+0

我會檢查你的建議的教程。我想我遵循你的解釋。謝謝您的幫助! – Gregory6106 2013-03-20 15:37:34