Sc4r
Sc4r

Reputation: 700

Continuing after an exception

class Bool():

    def __init__(self, mode):
        self._mode = mode

    def switch(self):  
        if self._mode is False:
            raise Exception
        self._mode = False

class Test():

    def __init__(self):
        self._lst = [False, True, False, True]

    def __str__(self):
        return "list: " + str(self._lst)

    def normal(self):
        for index, element in enumerate(self._lst):
            try:
                Bool(element).switch()
            except Exception:
                continue

The problem with my code is that the method normal doesn't appear to work. What it's supposed to do is take the lst and turn all the True's to False's by calling the switch method from another class. And if the element is False, instead of raising any exception it should just skip it and move on to the next element.

t1 = Test()
print(t1)
list: [False, True, False, True]
t1.normal()
print(t1)
list: [False, True, False, True]

however it should actually be:

t1 = Test()
print(t1)
list: [False, True, False, True]
t1.normal()
print(t1)
list: [False, False, False, False]

Upvotes: 0

Views: 63

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34146

You must change the values in _lst. Also, since switch() method doesn't return anything, you should store the instance of Bool, call its switch() method and then assign it to the respective element in _lst

def normal(self):
    for index, element in enumerate(self._lst):
        try:
            b = Bool(element)  # Store instance
            b.switch()
            self._lst[index] = b._mode  # Change the respective element
        except Exception as e:
            print e  # Just for debug

Upvotes: 3

Related Questions