CMU 15-110: Principles of Computing
Object-Oriented Programming (OOP): Part 2
Writing Methods


  1. Turning Functions into Methods
  2. Advantages of Methods

  1. Turning Functions into Methods
    • Start with this (adapted from here):
      class Monster(object): def __init__(monster, cx, cy, r): monster.cx = cx monster.cy = cy monster.r = r def monsterContainsPoint(monster, x, y): d = ((monster.cx - x)**2 + (monster.cy - y)**2)**0.5 return (d <= monster.r) monsters = [ Monster(50, 50, 20), Monster(50, 50, 100), Monster(100, 100, 200) ] for monster in monsters: print(monsterContainsPoint(monster, 0, 0))

    • Turn the function into a (renamed) method, and the function call into a method call, like this:
      class Monster(object): def __init__(monster, cx, cy, r): monster.cx = cx monster.cy = cy monster.r = r def containsPoint(monster, x, y): d = ((monster.cx - x)**2 + (monster.cy - y)**2)**0.5 return (d <= monster.r) monsters = [ Monster(50, 50, 20), Monster(50, 50, 100), Monster(100, 100, 200) ] for monster in monsters: print(monster.containsPoint(0, 0))

  2. Advantages of Methods
    • Encapsulation
      • Organizes code
        A class includes the data and methods for that class.
      • Restricts access
        • len is a function, so we can call len(True) (which crashes)
        • upper is a method on strings but not booleans, so we cannot even call True.upper()
    • Polymorphism (same method name can run different code based on type)
      class Dog(object): def speak(dog): print('woof!') class Cat(object): def speak(cat): print('meow!') for animal in [ Dog(), Cat() ]: animal.speak() # same method name, but one woofs and one meows!