

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Methods
incomplete
3: Methods Can Return
incomplete
4: Methods vs. Functions
incomplete
5: Constructors
incomplete
6: Constructor Quiz
incomplete
7: Multiple Objects
incomplete
8: Objects Quiz
incomplete
9: Archer Practice
incomplete
10: Class Variables vs. Instance Variables
incomplete
11: Classes Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
So you might be wondering why classes are useful, they're like dictionaries... but worse... Right?
Well, no. First of all, classes provide structure. The class definition says "hey, I have these specific properties". A dictionary is more powerful in the sense that you can store whatever you want in it, but that also makes it less clear what on earth is in there at any given time.
Another thing that makes classes useful is that they can have methods! A method is just a function that's tied directly to a class and has access to its properties. See the take_damage method here:
class Soldier:
health: int = 5
# This is a method that reduces the
# health of the soldier
def take_damage(self, damage: int) -> None:
self.health -= damage
soldier_one = Soldier()
soldier_one.take_damage(2)
print(soldier_one.health)
# prints "3"
soldier_two = Soldier()
soldier_two.take_damage(1)
print(soldier_two.health)
# prints "4"
Methods are defined within the class declaration. Their first parameter is always the instance of the class that the method is being called on. By convention, it's called "self", and because self is a reference to the object, you can use it to read and update the properties of the object.
Notice that methods are called directly on an object instance using the dot operator:
my_object.my_method()
Complete the fortify(self) -> None method on the wall class. It should double the current armor property.