2013-12-12 45 views
-5

首先,我們可以將對象添加到Python字典中嗎?其次,我們如何打印對象的屬性。 有我的代碼從字典打印對象的屬性-python

在我c.py

class C(object): 
    def __init__(self): 
     self.wage = 0.0 
    def setwage(self,wage): 
     self.wage=wage 
    def getwage(self): 
     return self.wage 

在我a.py

import c 
dustin = c.C() 

dustin.setwage(6.9) 
dic={} 

# can I add dustin as an object into dic? 
dic['1st employee']=dustin 

for a in dic.items(): 
    # I want to print dustin object's attribute wage 
    print("wage:", a.getwage()) 
+0

你怎麼可能有如此高的聲譽,並不能解決像這樣簡單的事情? –

+1

@詹姆斯米爾一個*編輯*問題不是一個*問* – alko

+0

哦,我明白了嗎?!我很困惑:) –

回答

2

你當時幾乎沒有;要遍歷所有的字典

for a in dic.values(): 
    print("wage:", a.getwage()) 

另外,一本字典的項目中循環時,使用的事實,即每個項目是(key, value)一個元組:

for key, value in dic.items(): 
    print(key, "wage:", value.getwage()) 

所以,是的,你可以將實例存儲在字典中(大多數python都使用這個事實)。

請注意,getters和setter在Python中並不是真的需要;您可以簡化代碼:

class C(object): 
    def __init__(self): 
     self.wage = 0.0 

,然後使用:

dustin = c.C() 

dustin.wage = 6.9 
dic = {} 

dic['1st employee'] = dustin 

for key, value in dic.items(): 
    print(key, "wage:", value.wage) 

例如直接訪問wage屬性。

+0

我更新了上一個問題。再添加一個文件。現在我想從我之前創建的詞典中打印出列表。 http://stackoverflow.com/questions/20551917/print-list-in-a-dictionary-python – user3095795