Python类继承理解

4

我希望能够更好地理解如何使用Python类继承。

我在网上找到了以下问题。

创建一个家具类(Furnishing class),在实例化时应要求提供一个room参数。然后,创建以下继承自Furnishing类的类:SofaBookshelfBedTable

使用内置列表类型记录与上述类匹配的家中家具。例如,你可能会有:

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

现在,编写一个map_the_home()函数将其转换为内置的dict类型,其中房间是单独的键,关联值是该房间的家具列表。如果我们对命令行显示的内容运行该代码,我们可能会看到:
>>> 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个回答

1
这将会很容易,就像这样:

它只需要:

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

不是吗?


是的,我正在尝试那个,但是沙发类需要什么? - Trying_hard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接