Class Notes: Object-Oriented Programming (OOP), Part 1
Using Objects and Writing Classes


  1. Methods vs Functions
  2. Classes and Instances
  3. Objects and Object-Oriented Programming (OOP)
  4. Writing Classes
  5. Writing Constructors
  6. Writing Methods
  7. Advantages of Classes and Methods
  8. Objects and Aliases
  9. Example: Animations with OOP


  1. Methods vs Functions
  2.  
    We call methods using s.f() rather than f(s):
    s = 'This could be any string!'
    
    print(len(s))     # len is a function
    
    print(s.upper())  # upper is a string method, called using the . notation
                      # we say that we "call the method upper on the string s"
    
    print(s.replace('could', 'may')) # some methods take additional arguments

    See how we get different errors for improperly calling methods vs functions:
    n = 123
    print(len(n))    # TypeError: object of type 'int' has no len()
                     # This means that len() cannot work properly with int's
    
    n = 123
    print(n.upper()) # AttributeError: 'int' object has no attribute 'upper'
                     # This means that there is no method upper() for int's

  3. Classes and Instances
  4.  

  5. Objects and Object-Oriented Programming (OOP)
  6.  

  7. Writing Classes
  8. # Create our own class:
    class Dog:
        # a class must have a body, even if it does nothing, so we will
        # use 'pass' for now...
        pass
    
    # Create instances of our class:
    d1 = Dog()
    d2 = Dog()
    
    # Verify the type of these instances:
    print(type(d1))             # Dog (actually, class '__main__.Dog')
    print(isinstance(d2, Dog))  # True
    
    # Set and get properties (aka 'fields' or 'attributes') of these instances:
    d1.name = 'Dot'
    d1.age = 4
    d2.name = 'Elf'
    d2.age = 3
    print(d1.name, d1.age) # Dot 4
    print(d2.name, d2.age) # Elf 3

  9. Writing Constructors
  10. Writing Methods
  11. Advantages of Classes and Methods
  12. Objects and Aliases

  13. # Objects are mutable so aliases change!
    # Run this with the visualizer to make it clear!
    
    import copy
    
    class Dog:
        def __init__(self, name, age, breed):
            self.name = name
            self.age = age
            self.breed = breed
    
    dog1 = Dog('Dino', 10, 'shepherd')
    dog2 = dog1            # this is an alias
    dog3 = copy.copy(dog1) # this is a copy, not an alias
    
    dog1.name = 'Spot'
    print(dog2.name) # Spot (the alias changed, since it is the same object)
    print(dog3.name) # Dino (the copy did not change, since it is a different object)

  14. Example: Animations with OOP
  15. Here is an updated version of the adding-and-deleting dots demo from here. This version adds methods to the Dot class so each dot is responsible for its own drawing and mouse handling.
    from cmu_112_graphics import *
    import random
    
    class Dot:
        def __init__(self, cx, cy, r, counter, color):
            self.cx = cx
            self.cy = cy
            self.r = r
            self.counter = counter
            self.color = color
    
        def redraw(self, app, canvas):
            # Only redraw this dot
            canvas.create_oval(self.cx-self.r, self.cy-self.r,
                               self.cx+self.r, self.cy+self.r,
                               fill='white', outline=self.color, width=15)
            canvas.create_text(self.cx, self.cy, text=str(self.counter),
                               fill='black')
    
        def containsPoint(self, x, y):
            return (((self.cx - x)**2 + (self.cy - y)**2)**0.5 <= self.r)
    
        def mousePressed(self, event):
            # We are guaranteed (event.x, event.y) is in this dot
            self.counter += 1
            self.color = getRandomColor()
    
        def timerFired(self, app):
            self.counter += 1
    
    def appStarted(app):
        app.dots = [ ]
        app.timerDelay = 1000 # once per second
    
    def getRandomColor():
        colors = ['red', 'orange', 'yellow', 'green', 'blue', 'pink',
                  'lightGreen', 'gold', 'magenta', 'maroon', 'salmon',
                  'cyan', 'brown', 'orchid', 'purple']
        return random.choice(colors)
    
    def mousePressed(app, event):
        # go through dots in reverse order so that
        # we find the topmost dot that intersects
        for dot in reversed(app.dots):
            if dot.containsPoint(event.x, event.y):
                dot.mousePressed(event)
                return
        # mouse click was not in any dot, so create a new dot
        newDot = Dot(cx=event.x, cy=event.y, r=20, counter=0, color='cyan')
        app.dots.append(newDot)
    
    def keyPressed(app, event):
        if (event.key == 'd'):
            if (len(app.dots) > 0):
                app.dots.pop(0)
            else:
                print('No more dots to delete!')
    
    def timerFired(app):
        for dot in app.dots:
            dot.timerFired(app)
    
    def redrawAll(app, canvas):
        for dot in app.dots:
            dot.redraw(app, canvas)
    
        # draw the text
        canvas.create_text(app.width/2, 20,
                           text='Example: Adding and Deleting Shapes',
                           fill='black')
        canvas.create_text(app.width/2, 40,
                           text='Mouse clicks outside dots create new dots',
                           fill='black')
        canvas.create_text(app.width/2, 60,
                           text='Mouse clicks inside dots increase their counter',
                           fill='black')
        canvas.create_text(app.width/2, 70,
                           text='and randomize their color.', fill='black')
        canvas.create_text(app.width/2, 90,
                           text='Pressing "d" deletes circles', fill='black')
    
    runApp(width=400, height=400)