Reputation: 2419
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.
Upvotes: 0
Views: 1239
Reputation: 879849
To call the method switch
, use self.switch(i)
not switch(i)
:
def switch_every(self, n):
for i in range(0,len(self.switches), n):
self.switch(i) # <-- Change here
To get some readable output when you call
print (my_switchboard)
change the LightSwitch.__str__
method to LightSwitch.__repr__
:
def __repr__(self): # <-- Change `__str__` to `__repr__`
if self.switch == True:
return "I am on"
if self.switch == False:
return "I am off"
This is because, when you print a list, the repr
of its contents are printed.
The LightSwitch.flip
method could be shortened to:
def flip(self):
self.switch = False if self.switch else True
using a conditional expression.
Upvotes: 2