UberNate
UberNate

Reputation: 2419

How to operate a SwitchBoard that turns on the following switches within a sequence n? Python 3x

I wand to build a class SwitchBoard with the following properties:

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

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

Answers (1)

unutbu
unutbu

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

Related Questions