Python:遍历对象列表中的对象列表

6 python

我做了两个名为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  
####################
Run Code Online (Sandbox Code Playgroud)

And*_*ark 5

目前,您使用的是类属性而不是实例属性.尝试将类定义更改为以下内容:

class House:
    def __init__(self):
        self.ID = ""
        self.window_list = []

class Window:
    def __init__(self):
        self.ID = ""
Run Code Online (Sandbox Code Playgroud)

您的代码现在所有实例的方式House都是相同的window_list.