CMU 15-110: Principles of Computing
Object-Oriented Programming (OOP): Part 1
Creating Objects


  1. Getting Started
  2. A Better Example

  1. Getting Started
    # Defining a class and a constructor class Dog(object): def __init__(dog, name, age): dog.name = name dog.age = age # Creating instances (object) dog1 = Dog('Fido', 5) dog2 = Dog('Luna', 3) # Using instance variables print(dog1.name, dog1.age) # Fido 5 print(dog2.name, dog2.age) # Luna 3 dog2.age += 1 print(dog2.name, dog2.age) # Luna 4 # Using objects in functions def youngerAge(dog1, dog2): return min(dog1.age, dog2.age) print(youngerAge(dog1, dog2)) # 4 # Returning a new object in a function def makeChild(name, parent1, parent2): fullName = name + '-child-of-' + parent1.name + '-and-' + parent2.name return Dog(fullName, 0) dog3 = makeChild('Daisy', dog1, dog2) print(dog3.name, dog3.age) # Daisy-child-of-Fido-and-Luna 0

  2. A Better Example
    # Start with this file: events-starter-code.py class Monster(object): def __init__(monster, cx, cy, color, strength): monster.cx = cx monster.cy = cy monster.r = 20 monster.color = color monster.strength = strength def init(data): data.monsters = [ ] data.colors = ['red', 'orange', 'yellow', 'lightGreen', 'cyan'] data.colorIndex = 0 def getNextColor(data): nextColor = data.colors[data.colorIndex] data.colorIndex = (data.colorIndex + 1) % len(data.colors) return nextColor def monsterContainsPoint(monster, x, y): d = ((monster.cx - x)**2 + (monster.cy - y)**2)**0.5 return (d <= monster.r) def findMonster(data, x, y): for monster in data.monsters: if (monsterContainsPoint(monster, x, y) == True): return monster return None def mousePressed(event, data): monster = findMonster(data, event.x, event.y) if (monster == None): # did not click on a monster, so make a new one! monster = Monster(event.x, event.y, getNextColor(data), 5) data.monsters.append(monster) else: # clicked on a monster, so reduce its strength monster.strength -= 1 if (monster.strength == 0): data.monsters.remove(monster) def drawAll(canvas, data): # Title text canvas.create_text(data.width/2, 20, text='Creating Objects Demo!', font='Arial 26 bold') canvas.create_text(data.width/2, 50, text='Click to create monsters', font='Arial 20 bold') canvas.create_text(data.width/2, 80, text='Click on monsters to reduce strength', font='Arial 20 bold') canvas.create_text(data.width/2, 110, text='Monsters with zero strength disappear', font='Arial 20 bold') # Monsters for monster in data.monsters: canvas.create_oval(monster.cx-monster.r, monster.cy-monster.r, monster.cx+monster.r, monster.cy+monster.r, fill=monster.color) canvas.create_text(monster.cx, monster.cy, text=monster.strength, font='Arial 20 bold')