To Lecture Notes

IT 212 -- Oct 12, 2020

Review Exercises

  1. What are the dunder methods that you know? How are they invoked? Ans:
    Dunder
    Method
    Invoking
    Expression
    __init__ Constructor call, e.g.,
    p = Person("Alice", "F", 11)
    __str__ str(p) or print(p)
    __repr__ repr(p)
    __lt__ p < q
    __eq__ p == q
  2. How do you make objects of a class sortable?
    Ans: Supply an __lt__ method for the class, which defines an < operator.
  3. Look again at Practice Problem 1 in the October 7 Notes. Add a < operator method to your Person class to make the list of Person objects sortable. You can either make the Person objects sort in alphabetical order or in ascending order by age. Ans:
    # In class, we sorted by age:
    def __lt__(self, other):
        return self.age < other.age
        
    # To sort in alphabetic order by name:
    def __lt__(self, other):
        return self.name < other.name
    
    # In test3.py, to sort with either __lt__ method:
    persons.sort( )
    print(persons)
    
  4. Define a < operator for the Card class, where c1 < c2 if c1.rank < c2.rank. Now sort the list of Card objects by rank that we created on October 5 in the practice problem. Ans:
    #__lt__ method for Card class.
    def __lt__(self, other):
        return self.rank < other.rank
    
  5. Define a == operator for the Card class using the __eq__ operator. For two cards c1 and c2, c1 == c2 if their ranks are equal. Test your == operator.
    # __eq__ method for Card class
    def __eq__(self, other):
        return self.rank == other.rank
        
    # Unit test script test2.py to test == operator:
    import card
    import unittest
    
    class MyUnitTestClass(unittest.TestCase):
            
        def test_1(self):
            c = card.Card(12, 'H')  #<-- QH
            d = card.Card(12, 'S')  #<-- QS
            e = card.Card(14, 'C')  #<-- AC
            self.assertEqual(c == d, True)
            self.assertEqual(d == e, False)
            
    if __name__ == '__main__':
        unittest.main( )
    
    

Invoking Instance Methods

Project 3a

Introduction to Inheritance

Project 3b