Homework Solution

Defining a class

Problems to be Submitted (18 points)

  1. (5 points)

     1        class Radio():	                       #1) remove parentheses (OOPS: In Python 2.4, this used to be an explict error.  As of Python 2.5 and beyond the parentheses are spurious but not technically errant)
     2            def __init__(self):                      #2) 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   #3) _station is an instance variable
    13                
    14            def gotoPreset(self, ind):
    15                self._station = self._presets[ind]
    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
    

  2. (6 points)

        def scale(self, factor):
            for k in range(len(self._coords)):
                self._coords[k] *= factor
    

  3. (7 points)

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


Extra Credit

  1. (2 points)

    The simplest approach is to modify the togglePower method so as to read

        def togglePower(self):
          self._powerOn = not self._powerOn
          self._muted = False                 # will not remain muted after power is toggled
    


Last modified: Wednesday, 29 March 2017