I wand to build a class SwitchBoard with the following properties:
-
when I create a switchboard, I should be able to set the number of switches it contains
all switches should start in the “off” position -
if I print a switchboard, it should print something along the lines of: “The following switches are on: 1 3 5 7 9”
-
if I call switch(n) with n as an integer, it should ip the status of the n’th lightswitch
-
if I call switch every(n) with n as an integer, it should ip the status of every n’th lightswitch
I should be able to write a piece of global code that solves the lightswitch problem as stated above.
This is my work so far, the first is class LightSwitch
-
If switch is ON, it will flip and turn it OFF
-
If switch is OFF, it will flip and turn it ON
class LightSwitch():
def __init__(self, mode):
self.switch = mode
def __str__(self):
if self.switch == True:
return ("I am on")
if self.switch == False:
return ("I am off")
def turn_on(self):
self.switch = True
def turn_off(self):
self.switch = False
def flip(self):
if self.switch == True:
self.switch = False
else:
self.switch = True
And for the class SwitchBoard, this is what I have:
class SwitchBoard():
def __init__(self, n):
self.switches = []
for i in range(n):
self.switches.append(LightSwitch(False))
def switch(self, n):
self.switches[n].flip()
def switch_every(self, n):
for i in range(0,len(self.switches), n):
switch(i)
def __str__(self):
return "The following switches are on: " + str(self.switches)
if __name__ == ('__main__'):
my_light = LightSwitch(False)
my_light.flip()
print (my_light) # This prints "I am on"
my_light2 = LightSwitch(True)
my_light2.flip()
print(my_light2) # This prints "I am off"
my_switchboard = SwitchBoard(10) # This is the issue.
my_switchboard.switch_every(2)
print (my_switchboard)
This isn’t working out, I’m using a list to append the number of OFF switches but I’m not sure how to write global code to solve this issue, such as turning on switches within a sequence, or maybe something is missing, please help.
To call the method
switch, useself.switch(i)notswitch(i):To get some readable output when you call
change the
LightSwitch.__str__method toLightSwitch.__repr__:This is because, when you print a list, the
reprof its contents are printed.The
LightSwitch.flipmethod could be shortened to:using a conditional expression.