

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
We've already worked with both class variables and instance variables, but we haven't really talked about the difference.
Instance variables vary from object to object and are declared in the constructor. They're more common:
class Wall:
def __init__(self) -> None:
self.height = 10 # instance variable (per object)
south_wall = Wall()
south_wall.height = 20 # only updates this instance of a wall
print(south_wall.height)
# prints "20"
north_wall = Wall()
print(north_wall.height)
# prints "10"
Class variables are shared between instances of the same class and are declared at the top level of a class definition. They're less common:
class Wall:
height: int = 10 # class variable (shared across all instances)
south_wall = Wall()
print(south_wall.height)
# prints "10"
Wall.height = 20 # updates all instances of a Wall
print(south_wall.height)
# prints "20"
In other languages these types of variables are often called static variables.
Generally speaking, stay away from class variables. Just like global variables, class variables are usually a bad idea because they make it hard to keep track of which parts of your program are making updates. However, it is important to understand how they work because you may see them in the wild.
Some lazy class variable code written by another dev team at Age of Dragons Studios is causing bugs in our team's Dragon class.
In the main() function (that our team isn't responsible for) the line:
Dragon.element = "fire"
should not affect our existing Dragon instances! The Dragon class should be safe to use in other parts of the codebase, even if silly developers are out there changing class-level variables.
Fix the Dragon class.