Bound to It
August 3, 2022 ยท View on GitHub
Objectives
Kratos, angry developer, wanted to track the count of how many instances are created out of the class "Car". This is the code he wrote:
count = 0
class Car:
def __init__(self, color):
count += 1
self.color = color
print(f"Before: {count}")
car = Car("Red")
print(f"After: {count}")
- What's the problem with the code? What exception will it raise?
- What would you suggest Kratos to fix it?
Solution
-
In Python a variable inside a function is local. So when we try to increment count inside
__init__it fails since count isn't assigned with a value. It is NOT thecountdefined above the classCar. The exception raised isUnboundLocalError. In other words, you have a local variable that isn't assigned with a variable and you try to access the value of that variable anyway. -
Use class attributes:
class Car:
count = 0
def __init__(self, color):
count += 1
self.color = color
print(f"Before: {count}")
car = Car("Red")
print(f"After: {count}")
Another common solution is to use global this way
def __init__(self, color):
global count
count += 1
self.color = color
But this is not recommended and it's better to avoid it.