1

I don't know how to fix it but I think my code is clear. I am a beginner level python learner.

Here, I made a class Hero that has the method attack. However, when I called the method it says, there is an error 'int' object is not callable.

class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
      self.name = name
      self.health = hp
      self.attack = att_pwr
      self.defense = def_pwr

    def attack(self):
      print(self.name + ' is attacking')


Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()
Redowan Delowar
  • 1,580
  • 1
  • 14
  • 36

3 Answers3

2

Look closely, you have an attribute and a method named attack. The class is trying to call the attribute instead of the method. Here is the class that works!

class Hero:
    def __init__(self, name, hp, att_pwr, def_pwr):
        self.name = name
        self.hp = hp
        self.att_pwr = att_pwr
        self.def_pwr = def_pwr

    def attack(self):
        return self.name + " is attacking"


Hero1 = Hero("Arif", 75, 50, 40)
Hero1.attack()

This prints out:

>> 'Arif is attacking'
Redowan Delowar
  • 1,580
  • 1
  • 14
  • 36
  • 1
    Thanks for your help iam still a beginner so i didnt know its works like that. Can you share python exercises espicialy for data science to me? Maybe a link or web. It will very helpful for me – Evan Ariawan Feb 16 '20 at 05:27
0

This is because you have an attribute called attack as well as a method with the same name. Maybe you should rename the attack attribute to something else, for example attack_points.

class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
        self.name = name
        self.health = hp
        self.attack_points = att_pwr
        self.defense = def_pwr

    def attack(self):
        print(self.name + ' is attacking')


Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()
Peter Emil
  • 573
  • 3
  • 13
0

This is an object class and attack is a property so, you'll use -

Hero1.attack
Raihan Kabir
  • 447
  • 2
  • 10