不支持的操作数为3个实例的两个类和一个方法? [英] unsupported operand for 3 instances of two classes and one method?
问题描述
我试图让程序从 enemyUnit
获得hp stat,来自单位的攻击统计
,以及来自 tackle
的伤害统计,并将它们放入方法 getHit()
中的一个数学问题。这是代码:
I'm trying to get the program to take the hp stat from enemyUnit
, the attack stat from unit
, and the damage stat from tackle
and put them into one math problem in the method getHit()
. this is the code:
class Pokemon(object):
def __init__(self,hp,attack,defence):
self.hp = hp
self.attack = attack
self.defence = defence
def getHit(self,damage,hp,attack):
self.hp -= damage * self.attack/self.defence
print str(self.hp)
class Move(object):
def __init__(self,damage):
self.damage = damage
unit = Pokemon(10,2,3)
enemyUnit = Pokemon(4,2,3)
tackle = Move(3)
enemyUnit.getHit(enemyUnit,tackle,unit)
不幸的是它给我的错误
unsupported operand type(s) for *: 'Pokemon' and 'int'
如何让它从每个类的所有实例获取所有的变量,一个函数?
how do I get it to take all the variables from all instances of each class and put them into one function?
推荐答案
在 getHit()
参数:
-
hp
-
攻击
-
防御
hp
attack
defence
但是当你在 enemyUnit.getHit(enemyUnit,tackle,unit)
enemyUnit ,它是 Pokemon
类的一个对象。这会导致错误。
but when you call it in enemyUnit.getHit(enemyUnit, tackle, unit)
you are passing enemyUnit
which is an object of the Pokemon
class. This causes the error.
您可能需要传递正确的参数:
You may want to pass the correct parameters in:
enemyUnit.getHit(...) # Correct the parameters
我认为最好的想法是实现 getHit()
/ p>
I think the best idea would be to implement the getHit()
method like this:
def getHit(self, other, move):
self.hp -= move.damage * other.attack / self.defence
print str(self.hp)
p>
and call it with:
enemyUnit.getHit(unit, tackle)
请注意,您传递的是 hp
和攻击
c $ c> Pokemon 。您可以通过调用 obj.hp
和 obj.attack
来使用它们。
Note that you were passing hp
and attack
, which are attributes of Pokemon
. You can use them by just calling obj.hp
and obj.attack
.
这篇关于不支持的操作数为3个实例的两个类和一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!