如何附加一个类的实例,然后在Python中提取一个实例的属性?

时间:2015-12-13 23:03:33

标签: python

我正在创建一个文本冒险游戏。

我创建了一个类,并创建了几个不同的类实例。 该类有许多属性。我试图将类的每个实例附加到列表中。 然后我希望能够从列表中的一个实例中提取一个属性。

我被告知要实施:

“不要让每个房间都是[描述,北,东,南,西]的列表,而是创建一个Room类。该类应该有一个构造函数(描述,北,东,南,西)和设置描述和所有方向的字段。让程序使用新类。“

这是我到目前为止的代码:

room_list = []

class Room():
    def __init__(self, describe, nw, n, ne, e, se, s, sw, w):
        self.description = describe
        self.northwest = nw
        self.north = n
        self.northeast = ne
        self.east = e
        self.southeast = se
        self.south = s
        self.southwest = sw
        self.west = w

kitchen = Room("You are in the Kitchen. Look at the scrumptious roast chicken and kidney pudding! \nThere are doors leading to North, East, and West.", None, 4, None, 2, None, None, None, 0)

room_list.append(kitchen)

east_cooridor = Room("You apparated into the East Corridor. \nYou can apparate to the Northwest or the Southwest.", 8, None, None, None, None, None, 2, None)

room_list.append(east_cooridor)

great_hall = Room("You are in the Great Hall. What is that great smell? \nThere appears to be doors leading to the north and the south.", None, 7, None, None, None, 1, None, None)

room_list.append(great_hall)

west_cooridor = Room("You apparated into the West Corridor. \nYou can apparate to the Northeast or the Southeast.", None, None, 6, None, 0, None, None, None)

room_list.append(west_cooridor)

owlery = Room("You are in the Owlery. WHOOs got mail? There is a glass door overlooking the Forbidden Forest. \nThere are doors in every direction.", None, 9, None, 8, None, 4, None, 6)

room_list.append(owlery)

forbidden_forest = Room("Yikes! You are in the Forbidden Forest! Is that a dead unicorn? ...Or is it Aragog? \nGet back into the Owlery, quick! \nOf course...if you wanted to explore the forest more, you could certainly try!", None, None, None, None, None, 7, None, None)

room_list.append(forbidden_forest)

current_room = 4
while done == False:
    print(room_list[current_room][0])

最后一行代码出错并说: builtins.TypeError:'Room'对象不支持索引

相反,我希望它能够提出“你是在猫头鹰.WOOOs收到邮件?有一扇玻璃门可以俯瞰禁林。从各个方向都有门”。

到目前为止,我所尝试的并没有奏效。我很感激任何可能的建议。谢谢!

1 个答案:

答案 0 :(得分:3)

听起来你并不真正理解属性是如何工作的。类中的属性通常不能作为数组访问。如果你想打印一个房间的描述,你应该明确地调用属性:

current_room = 4
while not done:  # In python, "not done" is preferred over "done == False"
    print(room_list[current_room].description)