Object Oriented Programming: Difficult Solutions
What Would Python Display?
class Character:
def __init__(self, name):
self.name = name
self.life = 5
def battle(self, opponent):
if self.life > opponent.life:
battle(self, opponent)
if opponent.life == 0:
print(self.name, “defeats“, opponent.name)
elif self.life == opponent.life:
self.battle = lambda x, y : y.life - 2
else:
opponent.life += self.life
self.life = 0
print(opponent.name, “defeats“, self.name)
def team_battle(self, team_members, opponent):
team = [self] + team_members
for t in team:
battle(t, opponent)
if opponent.life == 0:
return “Team victory!”
def __repr__(self):
return self.name
class Spiderman(Character):
def transfer(self, other):
other = Spiderman(other.name)
other.life += 5
return other.name + “is the new Spiderman of this universe”
def __repr__(self):
return Character.__repr__(self) + " is a hero!"
class Supervillain(Character):
def __init__(self, name):
super().__init__(self, name)
self.life = 10
battle = lambda self, opponent: opponent.life - self.life
peter_parker = Spiderman(“Peter Parker”)
miles = Character(“Miles”)
>>> miles
Miles
>>> prowler = Supervillain(“Uncle Aaron”)
>>> kingpin = Supervillain(“Wilson Fisk”)
>>> peter_parker.battle(kingpin)
Wilson Fisk defeats Peter Parker
>>> peter_parker.transfer(miles)
>>> miles
"Miles is the new Spiderman of this universe"
Miles is a hero!
>>> miles.battle(prowler)
None
>>> kingpin.battle(prowler)
Wilson Fisk defeats Uncle Aaron
>>> gwen = Spiderman(“Gwen”)
>>> peter = Spiderman(“Peter B Parker”)
>>> team1 = [gwen, peter]
>>> miles.team_battle(team1, kingpin)
>>> kingpin.life
13
peni = Spiderman(“Peni Parker”)
noir = Spiderman(“Noir”)
spiderham = Spiderman(“Peter Porker”)
team2 = [gwen, peter, peni, noir, spiderham]
miles.team_battle(team2)
"Team victory!"