0
Staying Alive properties
class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): self._lives -= 1 #your code goes here @property def isAlive(self): return self._isAlive p = Player("Cyberpunk77", int(input())) i = 1 while True: p.hit() print("Hit # " + str(i)) i += 1 if not p.isAlive: print("Game Over") break isAlive not a member of Player class and where does the code go from there?
5 odpowiedzi
+ 4
##AS SIMPLE AS POSSIBLE## BEST SOLUTION##👌👌👌
class Player:
def __init__(self, name, lives):
self.name = name
self._lives = lives
def hit(self):
self._lives -= 1
#your code goes here
@property
def isAlive(self):
return self._lives > 0
p = Player("Cyberpunk77", int(input()))
i = 1
while True:
p.hit()
print("Hit # " + str(i))
i += 1
if not p.isAlive:
print("Game Over")
break
+ 1
'isAlive' is member of 'Player' class: it is defined as a @property method, meaning that when you access the property of same name (without parenthesis) under the hood the method is called...
however, inside the 'isAlive' method you try to return the value of '_isAlive' property, wich is not member of 'Player' class ^^
I guess you rather want to return the value of '_lives' member ;P
@property
def isAlive(self):
return self._lives
+ 1
@property
def isAlive(self):
return self._lives
@isAlive.setter
def isAlive(self, value):
if value>0:
self._lives=value
else:
self._lives=0
0
Eureka!
0
don't worry the exact answer is here✔✔✔😄✔✔✔
class Player:
def __init__(self, name, lives):
self.name = name
self._lives = lives
def hit(self):
self._lives -= 1
#your code goes here
@property
def isAlive(self):
if self._lives > 0:
return True
p = Player("Cyberpunk77", int(input()))
i = 1
while True:
p.hit()
print("Hit # " + str(i))
i += 1
if not p.isAlive:
print("Game Over")
break