15-112: Fundamentals of Programming and Computer Science
Class Notes: Object-Oriented Programming (OOP)
(Or, defining and using classes)



  1. Vocabulary
    You need to understand these terms, and in the case of specific methods, you need to know how and why to implement them.
    • struct, class, object, instance, type, isinstance
    • attribute, method, constructor, __dict__
    • function, method, static method, @staticmethod
    • subclass, superclass, super, inherit, override
    • __init__, __str__, __repr__, __eq__, __ne__, __add__, __radd__, __hash__

  2. Some examples of using classes
    print "Fraction example:"
    from fractions import Fraction
    f1 = Fraction(1,5)
    f2 = Fraction(2,7)
    f3 = f1 + f2
    print f1, "+", f2, "=", f3
    
    print "\n" + "datetime example:"
    from datetime import date
    today = date.today()
    print "today is", today
    halloween = date(today.year, 10, 31)
    if (today > halloween): halloween = date(today.year+1, 10, 31)
    timeToHalloween = (halloween - today)
    print "timeToHalloween =", timeToHalloween.days, "days"
    print "type(halloween) =", type(halloween)
    print "type(timeToHalloween) =", type(timeToHalloween)
    
    print "\n" + "webbrowser controller example:"
    import webbrowser
    browser = webbrowser.get()
    browser.open_new_tab("http://www.cs.cmu.edu/~112/schedule.html")
    

  3. Case Studies

  4. Previous notes with updates
    • You should know what __hash__ does and why it is required, but you will not be responsible for writing your own __hash__ methods.
    • You should use @staticmethod, and you can ignore @classmethod.
    • With that said, see these notes on classes .