【问题标题】:appending object to list of another object将对象附加到另一个对象的列表
【发布时间】:2020-05-09 19:38:59
【问题描述】:

我似乎无法将对象附加到不同对象的列表中。 尽我所能解释:

我是 python 新手,我正在尝试学习类和对象,所以我为自己准备了一个小 exe

我的程序中有 3 个对象:投资者、房屋和市场

在 Market 类中,我只有一个房屋清单

我有一个包含 3 个投资者的列表,每个投资者都有一个包含房屋列表的字段(从第一个 init 开始为空)

现在,我要做的是显示市场上的房屋列表(我已经完成了) 用户输入他想买的房子的索引,程序将该房子添加到他的房子列表中,并从市场上的房子列表中删除它。

现在我的问题似乎是,每次我选择一所房子时,它都会将其添加到所有 3 个投资者而不是特定的一个,我不知道为什么 (可能是因为它是 ref 类型,但我不知道如何克服它:/)

代码:

class Investor:
    def __init__(self, name, budget, houses):
        self.name = name
        self.budget = budget
        self.houses = houses

    def BuyHouse(self, market, houseIndex):
        self.budget -= market.availableHouses(houseIndex).price
        self.houses.append(market.availableHouses[houseIndex])  ## i believe this to be the problem. 
        print(f'Budget left: {self.budget}$')    

    def PrintAllInfo(self): # prints all info for houses.
        counter = 1
        for h in self.houses:
            print(f'{counter}) The House is in: {h.location}\n   The House price is: {h.price}$\n   The House size is: {h.size} sqft')
            counter += 1

class House:
    def __init__(self, location, price, length, width):
        self.location = location
        self.price = price
        self.width = width
        self.length = length

    def PrintThisHouse(self):
        print(f'{self.location}, Price - {self.price}$')

class Market:
    def __init__(self, availableHouses):
        self.availableHouses = availableHouses

    def PrintAllHouses(self):
        print('\nALL ABAILABLE PROPERTIES:\n--------------------------')
        counter = 1
        for h in self.availableHouses:
            print(str(counter) + ' - ', end='')
            counter += 1
            h.PrintThisHouse()

# main #
invHouses = []
investors = [ Investor('Bot1', 100000000, invHouses),
              Investor('Bot2', 100000000, invHouses),
              Investor('Bot3', 100000000, invHouses) ]
# init Houses:
houses = [ House("LA, California",450000,20,10),
           House("IL, Tel Aviv",1000000,5,5),
           House("Rus, Moscow",40000,20,10),
           House("Switz, Zr",125000,7,9),
           House("Fr, Paris",225000,15,4),
           House("Eg, Cairo",75000,15,15),
           House("Pt, Lisbon",100000,10,10),
           House("Ge, Batumi",75000,14,6),
           House("In, New Delhi",50000,20,20),
           House("Ca, Montreal",500000,30,35),
           House("Cambodia, Phnom Pen",15000,9,9),
           House("Uk, London",1000000,10,10) ]

#init Market:
mrkt = Market(houses)


# runs 3 times 1 time for each investor to buy one house.
for inv in investors: # run for all investors
    mrkt.PrintAllHouses() # a func that prints all the houses that are on the market
    selectHouse = (int(input('Enter the house you want to buy: ')) - 1)
    inv.BuyHouse(mrkt, selectHouse)


#after each investor bought a house i want to print for each investor his house(s) in the list
# problem is that now it prints all 3 houses for each one and i dont know why :(
for inv in investors:
    print(f'\nProperties of {inv.name}:')
    inv.PrintAllInfo()
    print('\n**************************')

非常感谢您的帮助,谢谢大家

【问题讨论】:

标签: python python-3.x list


【解决方案1】:
invHouses = []
investors = [ Investor('Bot1', 100000000, invHouses),
              Investor('Bot2', 100000000, invHouses),
              Investor('Bot3', 100000000, invHouses) ]

您有一个由invHouses 创建的列表对象。你把同样的东西传递给所有的投资者。因此,如果您通过一个投资者将房子添加到该列表中,所有其他投资者也会在他们的列表中获得该房子(因为它是相同的列表)。

investors = [ Investor('Bot1', 100000000, []),
              Investor('Bot2', 100000000, []),
              Investor('Bot3', 100000000, []) ]

改为将不同的对象传递给每个投资者。

【讨论】:

    【解决方案2】:

    我认为问题在于您将相同的清单 invHouses 传递给所有投资者。尝试在投资者的初始化中将 self.houses 初始化为空列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 2010-11-29
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多