2014-04-01 162 views
4

我想更好地理解如何使用python類繼承。python類繼承瞭解

我在網上發現了以下問題。

包括一個傢俱類。在實例化過程中,這個類應該請求一個room參數。然後,創建從Furnishing類繼承的以下類:Sofa,Bookshelf,BedTable

使用內置列表類型在家中錄製與上述類相匹配的傢俱。因此,例如,你可能有:

>>> from furnishings import * 
>>> home = [] 
>>> home.append(Bed('Bedroom')) 
>>> home.append(Sofa('Living Room')) 

現在,寫一個map_the_home()函數將其轉換成一個內置的字典類型,其中房間的各個鍵和相關的值是該房間的傢俱列表。如果我們撞上了什麼我們在命令行中顯示的代碼,我們可能會看到:

>>> map_the_home(home){'Bedroom': [<__main__.Bed object at 0x39f3b0>], 'Living Room':[<__main__.Sofa object at 0x39f3b0>]} 

我努力工作,與:

class Furnishing(object): 

    def __init__(self, room): 

     self.room = room 

class Sofa(Furnishing): 

    "Not sure how to get this into a dict"??? 

我不知道如何調用map_to_home(home)和讓它返回所需的dict

回答

1

這將是那麼容易,因爲:

def map_the_home(home): 
    result = dict([(a.room, a) for a in home]) 
    return result 

是不是?

+0

是的,我正在嘗試,但是我需要在沙發上上課嗎? –

+0

「沙發」有什麼問題? –

+0

沒什麼都好。謝謝 –