亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Python 中創建包含類實例的對象?

如何在 Python 中創建包含類實例的對象?

三國紛爭 2022-12-20 09:32:33
我想創建一個包含類的一些實例的對象。該對象應該是實例的某種列表泛化。例如,我有以下課程:class car:     def __init__(self, prize, color)         self.prize = prize         self.color = color現在我想要一個cars包含類汽車的許多實例的對象,但我可以像汽車實例一樣使用它,即cars.prize應該返回我在該對象中收集的所有實例的獎品列表cars。
查看完整描述

4 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

我認為你可以這樣做:


class Cars:

    def __init__(self, list_of_cars):

        self.cars_list = list_of_cars

        self.prize = [car.prize for car in self.cars_list]

        self.color = [car.color for car in self.cars_list]

讓我們看看如何使用它:


list_of_cars = [Car(1000, "red"), Car(2000, "blue"), Car(3000, "Green")]

x = Cars(list_of_cars)


print(x.prize)

# [1000, 2000, 3000]


print(x.color)

#["red", "blue", "Green"]


查看完整回答
反對 回復 2022-12-20
?
米脂

TA貢獻1836條經驗 獲得超3個贊

您可以創建一個class car_list()包含汽車列表的新列表(您可以向其添加、刪除等)。在該類中,添加一個get_prizes()通過遍歷列表返回獎品列表的方法。例如:


class car_list():

   def __init__(self, cars):

      self.cars = cars # This is a list


   def get_prizes(self):

      return [car.prize for car in self.cars]


查看完整回答
反對 回復 2022-12-20
?
MYYA

TA貢獻1868條經驗 獲得超4個贊

代碼中的小錯誤:您需要在方法定義行 :的末尾:__init__

def __init__(self, prize, color):


這是一個實現cars你想要的。裝飾器的使用@property允許您將方法作為對象屬性進行訪問:


class car:

    def __init__(self, prize, color):

        self.prize = prize

        self.color = color


class cars:

    def __init__(self, list_of_cars):

        for one_car in list_of_cars:

            assert isinstance(one_car, car) # ensure you are only given cars

        self.my_cars = list_of_cars


    @property

    def prize(self):

        return [one_car.prize for one_car in self.my_cars]


    @property

    def color(self):

        return [one_car.color for one_car in self.my_cars]



>>> a = car('prize1', 'red')

>>> b = car('prize2', 'green')

>>> c = car('prize3', 'azure')

>>> carz = cars([a,b,c])

>>> carz.prize

['prize1', 'prize2', 'prize3']

>>> carz.color

['red', 'green', 'azure']

如果需要,您可以在每個對象中添加更多的輸入檢查,但這是基本框架。希望它有所幫助,快樂編碼!


查看完整回答
反對 回復 2022-12-20
?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

這個答案的靈感來自 Sam 使用裝飾器的絕妙想法。因此,如果您認為自己對這段代碼感到滿意,請給他打分。


def singleton(all_cars):

    instances = {} # cars instances

    def get_instance():

        if all_cars not in instances:

            # all_cars is created once

            instances[all_cars] = all_cars()

        return instances[all_cars]

    return get_instance


@singleton

class all_cars:

    def __init__(self):

        self.inventory = {}


    @property

    def prizes(self):

        return [e.prize for e in self.inventory.values()]

    @property

    def colors(self):

        return [e.color for e in self.inventory.values()]        


class car:

    def __init__(self, prize, color):

        self.prize = prize

        self.color = color


    def register(self):

        # Like class all_cars is a singleton it is instantiate once, reason why dict is saved

        cars = all_cars()

        cars.inventory[len(cars.inventory)] = self



if __name__ == '__main__':

    # Creating cars items

    car1 = car("50", "Blue")

    car2 = car("300", "Red")

    car3 = car("150", "Gray")

    # Register part for cars

    car1.register()

    car2.register()

    car3.register()

    # Like class all_cars is a singleton it is instantiate once, reason why dict is saved

    cars = all_cars()


    print(cars.inventory)

    """{0: <__main__.car object at 0x7f3dbc469400>, ---> This is object car1

    1: <__main__.car object at 0x7f3dbc469518>,  ---> This is object car2

    2: <__main__.car object at 0x7f3dbc469550>}  ---> This is object car3"""

    print(cars.prizes)

    """['50', '300', '150']"""

    print(cars.colors)

    """['Blue', 'Red', 'Gray']"""



查看完整回答
反對 回復 2022-12-20
  • 4 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號