Search code examples
python-3.xclass-variables

Python - How to set an instance variable to a number in a Class variable list


Any tips on what I need to do to the method increase below which should increase the engine size variable I have based on the values available in the Class Variable list engine sizes?

E.g. If i set self.engine to 1.6 how can I check the Class Variable List engine_sizes and find the next biggest engine size and set it to that.

Below is the code I have so far:

class Car(object):
    engine_sizes = [1.1, 1.6, 1.8, 1.9]

    def __init__(self, make, model, engine):
       if engine not in self.engine_sizes:
        raise ValueError("%s is not a valid engine size." % engine)

        self.__make = make
        self.__model = model
        self.style = style
        self.engine = engine

     def increase(self):
        if self.engine == max(self.engine_sizes):
            print("Engine is too big to increase")
        else:
            self.engine = next(self.engine_sizes )
            print("Engine Size Updated")

Solution

  • You can't do this the way you've written the code, for a couple of reasons. One is that if you make engine_sizes a class variable, all the instances of the class will be sharing a reference to the same object. But more importantly because list objects are iterable, but they are not iterators.

    You could try something like this:

    class Car(object):
        engine_sizes = [1.1, 1.6, 1.8, 1.9]
    
        def __init__(self, make, model, engine):
           if engine not in self.engine_sizes:
               raise ValueError("%s is not a valid engine size." % engine)
    
            self.__make = make
            self.__model = model
            self.style = style
            self.engine = engine
    
         def increase(self):
            if self.engine == max(self.engine_sizes):
                print("Engine is too big to increase")
            else:
                idx = self.engine_sizes.index(self.engine)
                self.engine = self.engine_sizes[idx + 1]
                print("Engine Size Updated")