0
Help please ! This code works on sololearn playground but on vscode it gives an error : 'Alien' object has no attribute 'hit' !!
class Enemy: name = "" lives = 0 def __init__(self, name, lives): self.name = name self.lives = lives def hit(self): self.lives -= 1 if self.lives <= 0: print(self.name + ' killed') else: print(self.name + ' has '+ str(self.lives) + ' lives') class Monster(Enemy): def __init__(self): super().__init__('Monster', 3) class Alien(Enemy): def __init__(self): super().__init__('Alien', 5) m = Monster() a = Alien() while True: x = input() if x == 'laser': a.hit() elif x == 'gun': m.hit() if x == 'exit': break
7 Answers
+ 1
Are you sure this code is exactly what you used?
The fact that the error message says *attribute* 'hit' and not *method* 'hit' suggests that you used
a.hit
instead of
a.hit()
But in the code above that is not the case. So check if it's really exactly the same code.
+ 1
I suggest you double check indentation. But quite a picky check: make sure all have 2 or 4 spaces for nesting level.
Plus, check if you don't have tabs and spaces mixed. The right way is to use 2 or 4 multiples of spaces, not tabs.
Sometimes we mess these things up, and one platform forgives that, and other doesn't.
+ 1
Jenna The method name alone - hit - returns the method itself. If you assigned it to a variable, you could call the method later through the variable. But just having it as an statement doesn't execute the method. So no "hit".
The method with the parenthesis means method results, so the interpreter indeed runs it. So, a "hit".
The space between the method name and the parenthesis is wrong style, but I don't know if it's invalid syntax. Even if it is, some interpreters can be more "forgiving" and just ignore the space. But I'd search to know if it's valid syntax.
0
ola Scar
Alien and Monster both classes extends Enemy class so both classes can access all the properties or function of Enemy class so this error should not come.
0
Yes of course, and i don't understand why it raised this error
0
I just checked line by line it's the same code
0
Ran this code in only solo-learn playground...
Where a.hit() is written...
I tried
1) a.hit
2) a.hit ()
3) a.hit()
In first case, it didn't give any error/warning...just that it wouldn't consider the input laser at all... As if I have not given any laser as input only guns/exit as input...
I have no idea what is going on here? đđ»đ
In second case, it worked well but space was there...
____Is it even allowed? Like PEP8 doesn't allow it, right?? Please someone tellđ
In third case, well it is the right one... So, it worked fine...