我正在努力创造一个生命/愤怒(变量)下降时,让用户战斗一个骑士。我已经定义了一个叫做国王的职业,这是非常简单的,用于每个骑士,但我一直被告知,我没有正确地调用这个职业。我不知道该怎么解释。下面是职业和骑士的代码,错误信息将在底部。一些打印间距是奇怪的(那些与''' '''),因为网站是困难的。谢谢你!
类:class kingsmen:
def __init__(self):
self.stats = {}
def attributes(self):
health=15
anger=7
self.stats["health"] = 15 #storing default health count
self.stats["anger"] = 7
return self.stats
def warning(self): #players will see this message when meeting a knight
print ('A kingsmen! Prepare for battle!')
def noise(self):
print ("H e y , i t ' s a v i l l a g e r !") #have these attributes later.
def death(self):
if healh == 0:
print ('''DEFEATED''')
Knight: def rknightOne(kingsmen): #r stands for random, he will be one of 5 random villains you can face
rknightOne=kingsmen()
#while health in kingsmen.stats()!= 0 and anger != 0:
if action == 'attack':
for health in rknightOne.attributes:
health=health-1
print health
print_slowly ('I did not feel a thing. Ha ha ha!')
healthDrop(user)
elif action == 'mercy':
for anger in rknightOne.attributes:
anger=anger-1
print_slowly ('Huh. I feel something warm inside.')
elif action=='run':
print_slowly ('Not so fast!')
else:
print_slowly ("Jeez this guy is looney. I CAN'T UNDERSTAND YOU!")
错误:Traceback (most recent call last):
File "C:/Python27/REDEMPTION/Redemption Game V1.py", line 678, in <module>
print randomKnight()
File "C:/Python27/REDEMPTION/Redemption Game V1.py", line 440, in randomKnight
print random.choice([rknightOne(kingsmen), rknightTwo(kingsmen), rknightThree(kingsmen), rknightFour(kingsmen), rknightFive(kingsmen)])
File "C:/Python27/REDEMPTION/Redemption Game V1.py", line 178, in rknightOne
for health in rknightOne.attributes:
TypeError: 'instancemethod' object is not iterable
它所说的随机函数只是在5个可能出现的骑士之间循环。下面是代码,如果它对你有帮助的话:
def randomKnight():
print random.choice([rknightOne(kingsmen), rknightTwo(kingsmen), rknightThree(kingsmen), rknightFour(kingsmen), rknightFive(kingsmen)])
修改
for health in kingsmen.stats():
用下列语句之一
for health in kingsmen.stats: # if you don't want to call the method
for health in kingsmen.stats(some_argument): # or if you want to call the method provide arguments
你得到这个错误的原因是你已经定义了
self.stats = {}
和
def stats(self)
在kingsmen的课上,所以它让你感到困惑。
使用最新版本的代码,您现在要做的事情就很清楚了。您看到的错误消息告诉您不能迭代实例方法。这正是你想要做的。你在试图绕过国王。属性,它是类中的方法。你不能那样做。你的方法实际上是返回一个字典,执行那个方法的结果是你可以迭代的东西。因此,您实际上希望遍历调用attributes()的结果。然而,在此之前还有一个问题需要澄清,我将在下面解释。
为了能够正确地调用属性,你必须首先实例化你的类(Python中关于类和对象的文档)。
您所做的不是执行方法,而且,没有实例化类以能够访问和执行方法。
要解决这个问题,在这里写一行:
for health in kingsmen.attributes:
您需要首先实例化您的类,然后使用类中的对象调用attributes方法。你实现的那个属性方法的返回将返回你尝试遍历的字典。所以,你的代码应该是这样的:
my_kingsmen = kinsgmen()
for health in my_kinsgmen.attributes():