【发布时间】: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**************************')
非常感谢您的帮助,谢谢大家
【问题讨论】:
-
将来提供minimal reproducible example 会有所帮助。我敢打赌,你可以在四分之一的代码中重现同样的问题。
-
请不要在问题中加上“已解决”。而是通过单击左侧的复选标记接受您认为最有帮助的答案。见What should I do when someone answers my question?
标签: python python-3.x list