簡體   English   中英

我如何訪問實例變量項以從每個類中打印出唯一的項列表?

[英]How can I access instance variable, items in order to print out a unique list of items from every class?

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

請嘗試以下操作(未經測試)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM