AttributeError:' str'对象没有属性

时间:2014-05-28 13:34:39

标签: python attributeerror

我对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与字典中的数字连接是错误的,但我不知道该怎么做以及如何解决这个问题。

1 个答案:

答案 0 :(得分:5)

问题出在您的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或类似的东西。