Homework Solution

Defining a class

Problems to be Submitted (18 points)

  1. (5 points)

     1   class MyClass:
     2     def __init__(self):
     3       self._x = 1
     4         
     5     def increase(self):
     6       self._x += 1
     7           
     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. (7 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. (3 points)

    This code would be flawed. By invoking extend directly upon the list instance rather than with our SortedSet version of that method, duplicate entries are not removed and the initial values are not automatically sorted.

  4. (3 points)

    In this case, the code remains legitimate. The syntax len(self) is equivalent to len(self._items) based upon our implementation of SortedSet.__len__ Similarly, self[walk] is equivalent in result to self._items[walk] due to our implementation of the SortedSet.__getitem__ method.


Extra Credit

  1. (2 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.

Last modified: Wednesday, 17 April 2013