

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
I have a confession... I've been teaching you the bad way to define properties on a class... oopsie!
Click to play video
It's rare in the real world to see a class that defines properties like this (as we did):
class Soldier:
name: str = "Legolas"
armor: int = 2
num_weapons: int = 2
A constructor is (usually) better. It's a specific method on a class called __init__ that is called automatically when you create a new instance of a class.
So, using a constructor, the code from above would look like this:
class Soldier:
def __init__(self) -> None:
self.name = "Legolas"
self.armor = 2
self.num_weapons = 2
Not only is this safer (we'll talk about why later), but it also allows us to make the starting property values configurable:
class Soldier:
def __init__(self, name: str, armor: int, num_weapons: int) -> None:
self.name = name
self.armor = armor
self.num_weapons = num_weapons
soldier_one = Soldier("Legolas", 2, 10)
print(soldier_one.name)
# prints "Legolas"
print(soldier_one.armor)
# prints "2"
print(soldier_one.num_weapons)
# prints "10"
soldier_two = Soldier("Gimli", 5, 1)
print(soldier_two.name)
# prints "Gimli"
print(soldier_two.armor)
# prints "5"
print(soldier_two.num_weapons)
# prints "1"
Add a constructor to the Wall class.