Objects are not statues; they are alive! They can change over time.
A robot might start at Level 1, but we can write a spell to upgrade it.
Changing Self
Methods can do more than just print; they can modify the object's data.
class Hero:
def __init__(self):
self.hp = 100
def take_damage(self):
self.hp = self.hp - 10 # Change self!
hero = Hero()
hero.take_damage()
print(hero.hp) # 90
1
Define Upgrade
Inside Robot, define def upgrade(self):.
2
Modify Data
Inside the method, increase the level: self.level = self.level + 1 (or self.level += 1).
3
Multiple Upgrades
Call bot.upgrade() two times. Watch the level go from 1 to 2 to 3!
This is called "State". The object remembers its current status (Level 3), and methods change that status.
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
class Robot:
def __init__(self, name):
self.name = name
self.level = 1
def upgrade(self):
self.level = self.level + 1
print(self.name + " upgraded to level " + str(self.level))
bot = Robot("HoppyBot")
print("Start Level: " + str(bot.level))
bot.upgrade()
bot.upgrade()
print("Final Level: " + str(bot.level))Advanced TipsWant more? Click to expandClick to collapse
F. Encapsulation
- We keep the logic for upgrading inside the Robot.
- This is safer than manually typing
bot.level = bot.level + 1everywhere in your code. The Robot manages its own upgrades!
Loading...
Terminal
Terminal
Ready to run...