gpt4 book ai didi

python类继承理解

转载 作者:太空宇宙 更新时间:2023-11-03 11:52:23 25 4
gpt4 key购买 nike

我试图更好地理解如何使用 python 类继承。

我在网上发现了以下问题。

Include a Furnishing class. During instantiation, this class should ask for a room argument. Then, create the following classes that inherit from the Furnishing class: Sofa, Bookshelf, Bed, and Table.

Use the built-in list type to record the furniture in your own home that matches the classes above. So for example, you might have:

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

Now, write a map_the_home() function to convert that to a built-in dict type where the rooms are the individual keys and the associated value is the list of furniture for that room. If we ran that code against what we display in our command line, we might see:

>>> 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

最佳答案

这会很简单:

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

不是吗?

关于python类继承理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22789754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com