Classes(OOB)

Object Oriented Programming

Object oriented programming is very simply a way to make any number of objects
quickly with alot of the same basic attributes, such as variables, lists, even functions.
We make objects by first setting up a class structure, or a template for the objects.
Think of it as a factory to mass produce products. Here is your first example class.

class teddyBear: 
    def __init__(self, name): 
        self.name = name 
        self.price = 50 
        print self.name, "Teddy Bear created!" 
    def squeeze(self): 
        print "Squeak"

The first line of this code creates the class ‘teddyBear’. The second line is what we call
a constructor. init is short for initialize. This function is automatically called
when you make a new instance (new object) of the class. This allows us to define
variables of the class. self is used in every function except for static functions which
we will get to way later. We also use self to show that variables are solely for that
specific instance. Now that we have a class, we can create an object from it. Add these
lines after your class.

brown = teddyBear("Brown") #Create instance of class(object) called brown. 
brown.squeeze() #Use the squeeze function for this object 
print brown.name, "Teddy Bear costs", brown.price, "bucks!" #show price of
object

Just like a function, we added certain parameters to teddy bear which have to be met.
Name is the one parameter that we told it we needed to create that object. Had we
tried to create the object without that, we would’ve gotten an error. self is
automatically assigned the name of our object. In other words, in our instance ‘brown’,
the program replaces ‘self’ with ‘brown’. When calling a function or even a variable of
an instance (object), we use the object’s name then a period, then what it is we are
trying to call. Let’s make a simple game using objects (This is a higher/lower game
with levels):

import random #import random module 
class Level: #make a class for level objects 
    def __init__(self, cap, levelno): #when initializing, get cap and level
no. 
        self.cap = cap 
        self.number = random.randint(0, cap) #Get random number between 0
and cap
        self.level = levelno 
    def check_number(self, x): #Make function to tell if guess is high or
low 
        if x > self.number: 
            print "That number is too high!" 
            return False #If the number is higher, return false 
        elif x < self.number: 
            print "That number is too low!" 
            return False #if the number is lower, return false 
        else: 
            print "That's it! YOU PASSED THE LEVEL" 
            return True #if the number is equal to the right one, return
true       
level1 = Level(100, 1) 
level2 = Level(500, 2) 
level3 = Level(1000, 3) 
levels = [level1, level2, level3] 
x = 0 
currentlevel = levels[x] #set current level as level1 
print "Welcome to Higher or Lower! Good Luck!" 
print "Level", currentlevel.level, "\n\n" 
running = 1 
while running: #While true 
    guess = input("Please guess a number between 0 and %d:
"%currentlevel.cap)       
    if currentlevel.check_number(guess) == True: 
        x += 1 #bumps the index up for levels 
        if x >= len(levels): 
            print "\n\n\n\n CONGRATS! YOU WIN THE GAME!" #If you win the
last       level,  you win the game 
            running = 0 #game stops 

        else: 
            currentlevel = levels[x] #If not, go to the next level 
            print "\n\nLevel", currentlevel.level, "\n\n" #Show current
level

Ok, I know this is a huge amount of new code, but try to bear with me. First let’s look
at the class. We define a class called ‘Level’. When we initialize, starting with the
second line, we make it mandatory that each object has a cap, and a level number
when created. Now I know you are seeing a alot of “random” around here. Random is
a module that is included with python. It has many functions to randomize integers
and such. All we use is the randint() function in this program. This will pick a random
integer within the range specified (in our case 0-cap). By setting self.cap = cap, we
make it so it can be different for each object, the same with levelno. After that, we just
create a function within the class to check if the variable entered by the user, is higher
or lower. We then create three different objects from the same class, but with different
parameters (each a different cap and different level number). The line after that
creates a list with our levels inside of it. The reason we set x as 0 was so that we could
easily change the list index when we want to change our level. Then we have our
while statement… This will just loop the program until the player wins! So for our
loop, we get the user’s guess. Then we call our function with the next if statement. If
the player gets the number right, our function will return true and depending on the
level, bump it up, or tell the player they won and exit the loop!
Tell me if I need to add more context to this for your understanding in the Bulletin
Board. But first try these practices:

Practice

  1. Make it so the user can decide whether or not they want to play again
  2. Add a new level or two to the game
  3. Add lines to the program, so that the user can quit anytime by typing -1