我做了两个名为House and Window的课程。然后,我列出了包含四个房屋的清单。 House的每个实例都有一个Windows列表。我正在尝试遍历每个房子的窗户并打印它的ID。但是,我似乎得到了一些奇怪的结果:S我非常感谢任何帮助。
#!/usr/bin/env python
# Minimal house class
class House:
ID = ""
window_list = []
# Minimal window class
class Window:
ID = ""
# List of houses
house_list = []
# Number of windows to build into each of the four houses
windows_per_house = [1, 3, 2, 1]
# Build the houses
for new_house in range(0, len(windows_per_house)):
# Append the new house to the house list
house_list.append(House())
# Give the new house an ID
house_list[new_house].ID = str(new_house)
# For each new house build some windows
for new_window in range(0, windows_per_house[new_house]):
# Append window to house's window list
house_list[new_house].window_list.append(Window())
# Give the window an ID
house_list[new_house].window_list[new_window].ID = str(new_window)
#Iterate through the windows of each house, printing house and window IDs.
for house in house_list:
print "House: " + house.ID
for window in house.window_list:
print " Window: " + window.ID
####################
# Desired output:
#
# House: 0
# Window: 0
# House: 1
# Window: 0
# Window: 1
# Window: 2
# House: 2
# Window: 0
# Window: 1
# House: 3
# Window: 0
####################
答案 0 :(得分:5)
目前您正在使用class attributes instead of instance attributes。尝试将类定义更改为以下内容:
class House:
def __init__(self):
self.ID = ""
self.window_list = []
class Window:
def __init__(self):
self.ID = ""
您的代码现在的方式House
的所有实例共享相同的window_list
。
答案 1 :(得分:3)
答案 2 :(得分:2)
这是更新的代码。
# Minimal house class
class House:
def __init__(self, id):
self.ID = id
self.window_list = []
# Minimal window class
class Window:
ID = ""
# List of houses
house_list = []
# Number of windows to build into each of the for houses
windows_per_house = [1, 3, 2, 1]
# Build the houses
for new_house in range(len(windows_per_house)):
# Append the new house to the house list
house_list.append(House(str(new_house)))
# For each new house build some windows
for new_window in range(windows_per_house[new_house]):
# Append window to house's window list
house_list[new_house].window_list.append(Window())
# Give the window an ID
house_list[new_house].window_list[new_window].ID = str(new_window)
#Iterate through the windows of each house, printing house and window IDs.
for house in house_list:
print "House: " + house.ID
for window in house.window_list:
print " Window: " + window.ID
实际问题是window_list
属性是可变的,所以当不同的实例使用它时,它们最终会共享同一个属性。通过将window_list
移动到__init__
,每个实例都有自己的。
答案 3 :(得分:0)
除了一些缩进错误之外,您还要将ID
和window_list
分配给类,而不是实例。
你想要像
这样的东西class House():
def __init__(self, ID):
self.ID = ID
self.window_list = []
等
然后,您可以执行house_list.append(House(str(newHouse)))
等等。