2017-04-17 91 views
0

我想弄清楚如何在字典中存儲類Job的實例。我想達到這樣的{location : "London" , fee:500,fee:1200,location:"London" }。我通過將條目保存在類變量中嘗試了下面的解決方案,但我只能獲取該值。我無法定義密鑰。在Python中將類的實例存儲在字典中

class Job: 
    instances = dict() 
    rate = 1.04 

    def __init__(self, location, salary, description, fee) :  
     self.location = location 
     self.salary = salary 
     self.description = description 
     self.fee = fee 
     self.instances[self.location] = location 
     self.instances[self.fee] = fee 

    def Charge(self): 
     self.fee = int(self.fee + Job.rate) 



Job1 = Job("london",23000,"Accounts Assistant",1200) 
Job2 = Job("london",25000,"Accounts Assistant",500) 

print(Job.instances) 

輸出:

{1200: 1200, 'london': 'london', 500: 500} 

回答

0
def __init__(self, location, salary, description, fee) : 
    self.location = location 
    self.fee = fee 
    self.instances[self.location] = location 
    self.instances[self.fee] = fee 

這裏要設置的關鍵self.locationlocation,具有相同的價值。這就是每個鍵/值對重複的原因。使用self.instances["location"] = location將密鑰"location"設置爲location的值,對於fee也是如此。

+0

非常感謝你的建議這個作品 –