如何访问实例变量,项目以打印每个类的唯一项目列表?

时间:2018-01-15 22:52:06

标签: python python-3.x

class Trip(object):
    'a class that abstracts a trip to a destination'

    def __init__(self, destination='Nowhere', items=[] ):
        'Initialize the Trip class'
        self.destination = destination
        self.items = items

class DayTrip(Trip):
    'a class that abstracts a trip to a destination on a specific day'

    def __init__(self, destination='Nowhere', items=[] , day='1/1/2019' ):
        'Initialize the Trip class'
        self.destination = destination
        self.items = items
        self.day = day

class ExtendedTrip(Trip):
    'a class that abstracts a trip to a destination on between two dates'

    def __init__(self, destination='Nowhere', items=[] , day='1/1/2019' , 
endDay = '12/31/2019' ):
        'Initialize the ExtendedTrip class'
        self.destination = destination
        self.items = items
        self.day = day
        self.endDay = endDay

def luggage(lst):

我希望行李能够收集每个班级的所有物品,并打印出所有独特物品的清单。

这些是一些示例输入:

trip1 = Trip('Basement', ['coat','pants','teddy bear'])

trip2 = DayTrip('Springfield',['floss', 'coat','belt'], '2/1/2018')

trip3 = ExtendedTrip('Mars',['shampoo', 'coat','belt'], '4/1/2058')

trip4 = ExtendedTrip()

每次旅行都会附加到一个列表中,然后会有一组打印出来的项目列表:

{'pants', 'belt', 'toothbrush', 'floss', 'shampoo', 'teddy bear', 'coat'}

1 个答案:

答案 0 :(得分:0)

尝试以下内容(未经测试)。

def luggage(lst):
    items = set()
    for trip in lst:
        for item in trip.items:
            items.add(item)
    return items