属性错误: 'str'对象没有属性

27

我对Python编程还很陌生,想尝试制作一个简单的文字冒险游戏,但马上就遇到了难题。

class userInterface:
    def __init__(self, roomID, roomDesc, dirDesc, itemDesc):
        self.roomID = roomID
        self.roomDesc = roomDesc
        self.dirDesc = dirDesc
        self.itemDesc = itemDesc

    def displayRoom(self): #Displays the room description
        print(self.roomDesc)

    def displayDir(self): #Displays available directions
        L1 = self.dirDesc.keys()
        L2 = ""
        for i in L1:
                L2 += str(i) + " "
        print("You can go: " + L2)

    def displayItems(self): #Displays any items of interest
        print("Interesting items: " + str(self.itemDesc))

    def displayAll(self, num): #Displays all of the above
        num.displayRoom()
        num.displayDir()
        num.displayItems()

    def playerMovement(self): #Allows the player to change rooms based on the cardinal directions
        if input( "--> " ) in self.dirDesc.keys():
            letsago = "ID" + str(self.dirDesc.values())
            self.displayAll(letsago)
        else:
            print("Sorry, you can't go there mate.")



ID1 = userInterface(1, "This is a very small and empty room.", {"N": 2}, "There is nothing here.")

ID2 = userInterface(2, "This is another room.", {"W": 3}, ["knife", "butter"])

ID3 = userInterface(3, "This is the third room. GET OVER HERE", {}, ["rocket launcher"])

ID1.displayAll(ID1)
ID1.playerMovement()

这是我的代码,出现了某些原因导致了错误:
Traceback (most recent call last):
  File "D:/Python34/Text Adventure/framework.py", line 42, in <module>
    ID1.playerMovement()
  File "D:/Python34/Text Adventure/framework.py", line 30, in playerMovement
    self.displayAll(fuckthis)
  File "D:/Python34/Text Adventure/framework.py", line 23, in displayAll
    num.displayRoom()
AttributeError: 'str' object has no attribute 'displayRoom'

我在互联网和Python文档中搜索了一下,但不知道我在这里做错了什么。如果我将ID2或ID3放在self.displayAll(letsago)的位置上,它就可以完美地工作,但这是毫无意义的,因为玩家无法控制他想去哪里,所以我猜尝试将ID与字典中的数字连接有问题,但我不知道该怎么做和如何解决这个问题。

2
letsago是一个字符串,而不是userInterface的实例。 - Frédéric Hamidi
1
当您将房间的ID传递到.displayAll()时,请确保您要么a)在列表中查找房间并获取该房间(userinterface实例)然后调用.displayAll(),或者直接将userinterface实例传递到displayAll() - Henrik Andersson
一旦您的代码运行正常,请随意在Code Review上发布它,因为我有几个评论在这种情况下不适用。 :D - BeetDemGuise
1个回答

12
问题出现在你的playerMovement方法中。你正在创建房间变量的字符串名称(ID1ID2ID3):
letsago = "ID" + str(self.dirDesc.values())

然而,你创建的只是一个 str,它并不是变量。另外,我认为它并没有做你想做的事情。
>>>str({'a':1}.values())
'dict_values([1])'

如果你确实非常需要这种方式找到变量,你可以使用eval函数:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

或者使用 globals 函数:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

然而,我强烈建议您重新考虑一下您的类。您的 userInterface 类本质上是一个Room。它不应该处理玩家移动。这应该在另一个类中完成,比如GameManager


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接