gpt4 book ai didi

python - AttributeError: 'str' 对象没有属性

转载 作者:太空狗 更新时间:2023-10-29 18:34:17 25 4
gpt4 key购买 nike

我是 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 有问题使用字典中的数字,但我不知道该怎么做以及如何解决这个问题。

最佳答案

问题出在您的 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')

但是,我会强烈建议您重新考虑您的类(class)。您的 userInterface 类本质上是一个 Room。它不应该处理玩家的移动。这应该在另一个类中,可能是 GameManager 或类似的东西。

关于python - AttributeError: 'str' 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23913150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com