【问题标题】:How to append an instance of a class and then pull out an attribute of an instance in Python?如何附加一个类的实例,然后在 Python 中提取一个实例的属性?
【发布时间】:2015-12-13 23:03:32
【问题描述】:

我正在开发一款文字冒险游戏。

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

我被告知要实施:

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

这是我目前的代码:

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' 对象不支持索引

相反,我希望它从猫头鹰房中取出“你在猫头鹰店。谁收到邮件?有一扇玻璃门可以俯瞰禁林。每个方向都有门”。

到目前为止我所尝试的都没有奏效。我将不胜感激任何可能的建议。谢谢!

【问题讨论】:

  • 你希望从最后一行得到什么? room_list[current_room]Room,而你还没有实现 __getitem__
  • 当您从房间中拉出索引 [0] 时,您期望得到什么?是分配给“nw”的号码吗? p.s.听起来像 MajorMUD,我最喜欢的童年游戏之一 :)

标签: python


【解决方案1】:

听起来您并不真正了解属性的工作原理。类中的属性通常不能作为数组访问。如果你想打印房间的描述,你应该显式调用属性:

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

【讨论】:

  • 谢谢!我想我并没有意识到我不再列出清单,而是将它们用作属性。傻我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 2019-05-25
  • 2021-09-08
  • 2013-10-28
  • 1970-01-01
相关资源
最近更新 更多