use*_*799 10 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()
Run Code Online (Sandbox Code Playgroud)
那是我的代码,由于某种原因抛出了这个错误:
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'
Run Code Online (Sandbox Code Playgroud)
我在互联网和python文档中搜索到我在这里做错了什么,我不知道.如果我将ID2或ID3替换为self.displayAll(letsago),它可以完美地运行,但是由于玩家无法控制他想去的地方,所以这是没有意义的,所以我猜测尝试连接ID有什么问题使用字典中的数字,但我不知道该怎么做以及如何解决这个问题.
问题出在你的playerMovement方法上。你正在创建你的房间变量的字符串名称(ID1,ID2,ID3):
letsago = "ID" + str(self.dirDesc.values())
Run Code Online (Sandbox Code Playgroud)
但是,您创建的只是一个str。它不是变量。另外,我不认为它在做您认为在做的事情:
>>>str({'a':1}.values())
'dict_values([1])'
Run Code Online (Sandbox Code Playgroud)
如果您确实需要以这种方式查找变量,则可以使用以下eval函数:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
Run Code Online (Sandbox Code Playgroud)
或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')
Run Code Online (Sandbox Code Playgroud)
但是,我强烈建议您重新考虑上课。您的userInterface课程本质上是Room。它不应该处理玩家的动作。这应该在另一个类之内,也许GameManager是这样。