Homework Solution

Defining a class

Problems to be Submitted (20 points)

  1. (5 points)

     1   class MyClass:
     2     def __init__(self):
     3       self._x = 1
     4         
     5     def increase(self):
     6       self._x += 1
     6           
     8   class MyOtherClass(class MyClass):     # proper declaration of parent class
     9     def __init__(self, z):
    10       MyClass.__init__(self)             # must send self reference to parent constructor
    11       self._x = z
    12         
    13     def decrease(self):
    14       self._x -= 1                       # must use self reference to access inherited attribute
    15           
    16   a = MyClass()
    17   b = MyOtherClass(42)                   # constructor expects an actual parameter for z value
    18   b.increase()
    19   a.decrease()                           # MyClass instance does not support decrease method
    
  2. (5 points)

    class Student(Person):
      def __init__(self, name, age, id):
        Person.__init__(self, name, age)
        self.id = id
          
      def printInfo(self):
        Person.printInfo(self)
        print 'ID:', self.id
    
  3. (5 points)

    The initial appearance of a newly constructor star will be the same, but implicitly the reference point of that star will not be at its center, rather at its top point (the first point added to the underlying polygon). This distinction can be observed by subsequently rotating or scaling the star.

  4. (5 points)

    As written, the problem is that the names setWidth and setHeight are undefined when unqualified (such as when Rectangle.setWidth). This means that those lines will throw a NameError when executed. And since both Square.setWidth and Square.setHeight rely on a call to setSize, those will both fail.


Extra Credit

  1. (2 points)

    class RobustFile(file):
        
      def __init__(self, name, mode):
        success = False
        while not success:
          try:
            file.__init__(self, name, mode)   # try to initialize
            success = True
          except IOError:
            print 'Sorry.  Unable to open file', name, 'with specified mode.'
            name = raw_input('What is the filename? ')
    


Last modified: Friday, 16 April 2010