【问题标题】:How do I refer to an attribute of an object in a list, by using a string?如何使用字符串引用列表中对象的属性?
【发布时间】:2020-05-23 14:39:29
【问题描述】:

我正在编写一个文字冒险游戏,我正在尝试输入房间中的对象,在对象列表中搜索它,然后获取该对象并将其附加到库存 (inv) 列表中。我需要使用其名称的输入来搜索对象,这是属性之一。

class room():
    def __init__(self, name):
        self.objects = []

class player(room):
    def __init__(self, name, inv):
        self.name = name
        self.inv = []

class things(room):
    def __init__(self, name, is_weapon):
        self.name = name
        self.weapon = is_weapon



currentRoom = center
objLen = len(currentRoom.objects)
if currentRoom.objects:
    for x in range(len(currentRoom.objects)):
        print("Objects here: ",currentRoom.objects[x].name)
    pickUp = input("Would you like to take any objects: ")

    for a in range(0,objLen):
        if pickUp.upper() == currentRoom.objects.name:
            ind = currentRoom.objects.index(pickUp.upper().name)
            Andy.inv.append(currentRoom.objects[ind])
            currentRoom.objects.pop[ind]
        else:
            print("Object not found in this room!")

【问题讨论】:

  • class player(room):, class things(room):playerthings 不是 room?两者都可以驻留在room 中,但不应从它继承。
  • 使用字符串引用...列表中的对象?:在您的情况下,ind = aa是匹配pickUp.upper() == currentRoom.objects.name的对象的索引

标签: python python-3.x oop adventure


【解决方案1】:

知道了。

for a in range(0,objLen):
        if pickUp.upper() == currentRoom.objects[a].name:

            Player.inv.append(currentRoom.objects[a])
            currentRoom.objects.pop(a)

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2016-09-19
    • 2017-08-16
    • 2013-10-27
    相关资源
    最近更新 更多