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

1. Turning Functions into Methods
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))

• `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()`