Working through the coding challenges in Python, I reached exercise 4 in Classes (linked at the bottom) but couldn’t understand how I was supposed to set the class variables after they’d already been created with defaults.
The solution instructs me to create the class variables with default values, which I did as so:
class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
Then I’m supposed to set the variables so that every instance returns these values
DriveBot.all_disabled = True
DriveBot.latitude = -50.0
DriveBot.longitude = 50.0
What I don’t understand is WHERE the above code needs to go in order for the values to change, because every time I run the code with the print statements, I’m still getting the default values. Here is one version of the code I tried:
class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
self.all_disabled = False
self.latitude = -999999
self.longitude = -999999
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
robot_2 = DriveBot(35, 75, 25)
robot_3 = DriveBot(20, 60, 10)
DriveBot.longitude = 50.0
DriveBot.latitude = -50.0
DriveBot.all_disabled = True
print(robot_1.latitude)
print(robot_2.longitude)
print(robot_3.all_disabled)
This code outputs:
-999999
-999999
False
What do I need to do in order to have it output?
50.0
-50.0
True
The exercise can be found here (exercise 4):
Learn Python 3 | Codecademy