you're reading...

Defining Classes in Python

Screen Shot 2015-03-12 at 7.22.44 AM

Let’s design our first python class called Point.

class Point:
    def __init__(self,x=0,y=0):
    def __str__(self):
        return '(' + str(self.x) + ',' + str(self.y) + ')'
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def translate(self,dx,dy):
        self.x+= dx
        self.y += dy

def main():
    p1 = Point()
    print p1
    p2 = Point(3,4)
    print p2
    print p1 + p2
    print p2
    p3 = p1 + p2
    print p3

Mutli-Sided Die Class

A normal die (singular of dice) is a cube with six faces, each with a number from one to six. Some games use special dice with a different number of sides. Let’s design a generic class MSDie to model multi-sided dice. Each MSDie object will know two things: 1) How many sides it has. 2) It’s current value
When a new MSDie is created, we specify n, the number of sides it will have. We have three methods that we can use to operate on the die:

roll() – set the die to a random value between 1 and n, inclusive.
setValue() – set the die to a specific value (i.e. cheat)
getValue() – see what the current value is.

# msdie.py
# Class definition for an n-sided die.
from random import randrange

class MSDie:

    def __init__(self, sides):
        self.sides = sides
        self.value = 1

    def roll(self):
        self.value = randrange(1, self.sides+1)

    def getValue(self):
        return self.value

    def setValue(self, value):
        self.value = value

def main():
  die1 = MSDie(13)
  for  i in range(10):
      print die1.getValue() ,
#=> 12 9 12 13 10 10 7 11 1 7 12 4 10 3 7 7 2 11 12 7

Projectile Class

This class will need a constructor to initialize instance variables, an update method to change the state of the projectile, and getX and getY methods that can report the current position.
In the main program, a cannonball can be created from the initial angle, velocity, and height:cball = Projectile(angle, vel, h0)

import math
class Projectile:
    def __init__(self, angle, velocity, height):
        self.xpos = 0.0
        self.ypos = height
        theta = math.pi * angle / 180.0
        self.xvel = velocity * math.cos(theta)
        self.yvel = velocity * math.sin(theta)

    def getY(self):
        return self.ypos

    def getX(self):
        return self.xpos

    def update(self, time):
        self.xpos = self.xpos + time * self.xvel
        yvel1 = self.yvel - 9.8 * time
        self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
        self.yvel = yvel1

Problem: Write a client program that imports this Projectile class and constructs a projectile and determines the distance traveled by the projectile before it hits the ground.

#   cannonball.py
#   Simulation of the flight of a cannon ball (or other projectile)
#   This version imports a separate projectile module
import Projectiledef
def getInputs():
   a = input('Enter the launch angle (in degrees): ')
   v = input('Enter the initial velocity (in meters/sec): ')
   h = input('Enter the initial height (in meters): ')
   t = input('Enter the time interval between position calculations: ')
   return a,v,h,t
def main():
    angle, vel, h0, dtime = getInputs()
    cball = Projectile(angle, vel, h0)
    while cball.getY() > 0:
    print '\nDistance traveled (in meters): ', cball.getX()

1. For the Point class add the following methods:
set_location(), get_location(), distance_from_origin(), and distance_from(p) methods.
2. For the MSDie class add the following methods: getter and setter for the side instance variable. Also, write a client that constructs a pair of 6-sided dice and rolls and print the pair until doubles are reached.
3. Experiment with cannonball.py program. Use a for-loop over range of angles (say 40 to 50 degrees) to determine what angle gives the greatest distance when h0=0? Here you can fix the velocity and height and time interval. What angle (to nearest 0.1 of a degree) gives the greatest distance when h0=100, when h0=1000?


Here is a program which combines the graphics with the Projectile Class.

from graphics import *
from Projectiledef import *

def main():
    vel, h0, dtime = 100, 10, 0.1
    colors1 = ['red','magenta', 'maroon','pink', 'salmon','orange','yellow','green','navy','blue','purple','cyan']
    degrees= zip(range(40,65,2),colors1)
    win = GraphWin('My Cannonballs',1200, 600)
    for init_angle in degrees:
      cball = Projectile(init_angle[0], vel, h0)
      cballimg = Circle(Point(cball.getX(),cball.getY()), 10)
      while cball.getY() > 0:
        cballimg = Circle(Point(cball.getX(),cball.getY()),10)

    win.getMouse() # pause for click in window

Screen Shot 2015-03-12 at 7.22.44 AM



No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: