15-112: Fundamentals of Programming and Computer Science
Class Notes: Object-Oriented Programming (OOP)
(Or, defining and using classes)
- 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__
- 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")
- Case Studies
- MyFractionTester.py and MyFraction.py
- basicAnimationClass.py and basicAnimationDemo2WithClasses.py
- SmileyClassAnimationDemo.py
- SnakeClassAnimation.py (Note: this is an adaptation of snake8.py from this tutorial, adapted to work in this week's OOP-based MVC framework.)
- 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 .