Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - unsupported operand for 3 instances of two classes and one method?

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)

unfortunately it gives me the error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the getHit() method you are passing the arguments:

  • hp
  • attack
  • defence

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

Edit:

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)

and call it with:

enemyUnit.getHit(unit, tackle)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...