Homework Solution

Defining a class

Problems to be Submitted (18 points)

  1. (5 points)

     1        class Radio:
     2            def __init__(self):                              #1) constructor must be named __init__
     3                self._powerOn = False
     4                self._volume = 5
     5                self._station = 90.7
     6                self._presets = [ 90.7, 92.3, 94.7, 98.1, 105.7, 107.7 ]
     7        
     8            def togglePower(self):
     9                self._powerOn = not self._powerOn
    10        
    11            def setPreset(self, ind):
    12                self._presets[ind] = self._station           #2) _station is an instance variable, thus self._station
    13        
    14            def gotoPreset(self, ind):
    15                self._station = self._presets[ind]           #3) ind is a local parameter, and not an instance variable of self
    16        
    17            def increaseVolume(self):                        #4) Indentation of this line must be consistent with rest of the Radio class definition block
    18              self._volume = self._volume + 1
    19        
    20            def decreaseVolume(self):
    21                self._volume = self._volume - 1
    22        
    23            def increaseStation(self):                       #5) Must use colon when starting a new block
    24                self._station = self._station + .2
    25        
    26            def decreaseStation(self):
    27              self._station = self._station - .2             # Note: it is irrelevant whether indentation for body of this method matches indentation of other methods' bodies

  2. (10 points)

        def scale(self, factor):
            for k in range(len(self._coords)):
                self._coords[k] *= factor
    
        def __add__(self, other):
            dim = len(self._coords)
            combined = [self._coords[k] + other._coords[k] for k in	range(dim)]
            return Point(dim, combined)
    


Last modified: Saturday, 27 October 2018