AttributeError: 'str'对象没有属性
我刚开始学习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 个回答
12
问题出在你的 playerMovement
方法上。你在创建房间变量的名字字符串(ID1
、ID2
、ID3
):
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
或者类似的东西。