True/False
- True
- False
- False
- False (it may have more)
- False
- True
- False
- False
- False
- True
Multiple Choice
- b
- a
- d
- b
- c
- d
- c
- a
- c
- c
Discussion
- Instance variables live in objects and maintain their values as long as the object exists. They are accessed using dot notation. Regular variables are not accessed with dot notation and go away when the method terminates.
-
- A method is a function that "lives" in an object. The definition of a method looks like a function definition inside of a class. The first parameter of a method is self which refers to the object to which the method is being applied.
- A variable that "lives" inside an object. In the statement:
self.value = 1
value is an instance variable whose value is being set to 1. - A constructor is the method that constructs an object. In Python, it is a method named __init__
- An accessor is a method that returns the value of an isntance variable, for example:
def getValue(self): return self.value
- A mutator is a method that changes the value of one or more instance variables.
def roll(self): self.value = randrange(1,7)
-
Clowning around now. Creating a Bozo from: 3 Creating a Bozo from: 4 Clowning: 3 18 9 Clowning: 2 12 Clowning: 8 64 16
Programming Exercises
第一题
# projectile.py
"""projectile.py
Provides a simple class for modeling the flight of projectiles."""
from math import pi, sin, cos
class Projectile:
"""Simulates the flight of simple projectiles near the earth's
surface, ignoring wind resistance. Tracking is done in two
dimensions, height (y) and distance (x)."""
def __init__(self, angle, velocity, height):
"""Create a projectile with given launch angle, initial
velocity and height."""
self.xpos = 0.0
self.ypos = height
theta = pi * angle / 180.0
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
def update(self, time):
"""Update the state of this projectile to move it time seconds
farther into its flight"""
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
def getY(self):
"Returns the y position (height) of this projectile."
return self.ypos
def getX(self):
"Returns the x position (distance) of this projectile."
return self.xpos
#c10ex01.py
# Modification of cannonball to compute max height
from projectile import Projectile
def getInputs():
a = float(input("Enter the launch angle (in degrees): "))
v = float(input("Enter the initial velocity (in meters/sec): "))
h = float(input("Enter the initial height (in meters): "))
t = float(input("Enter the time interval between position calculations: "))
return a,v,h,t
def main():
print("Cannonball Simulation\n")
angle, vel, h0, time = getInputs()
cball = Projectile(angle, vel, h0)
maxHeight = h0
while cball.getY() >= 0:
cball.update(time)
if cball.getY() >maxHeight:
maxHeight = cball.getY()
print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))
print("Maximum height: {0:0.1f} meters.".format(maxHeight))
if __name__ == "__main__": main()
第三题
# c10ex03.py
# Three Button Monte
from random import randrange
from graphics import *
from button import Button
def main():
win = GraphWin("Three Button Monte", 350, 100)
win.setCoords(.5,0, 3.5, 3)
b1 = Button(win, Point(1,2), .75, 1, "Door 1")
b1.activate()
b2 = Button(win, Point(2,2), .75, 1, "Door 2")
b2.activate()
b3 = Button(win, Point(3,2), .75, 1, "Door 3")
b3.activate()
mess = Text(Point(2,.75), "Guess a door.")
mess.setStyle("bold")
mess.draw(win)
secret = randrange(1,4)
choice = None
while choice == None:
pt = win.getMouse()
for button in [b1, b2, b3]:
if button.clicked(pt):
choice = button
choiceNum = int(choice.getLabel()[-1])
if choiceNum == secret:
mess.setText("You win!")
else:
mess.setText("You lose. The answer was door {0}.".format(secret))
win.getMouse()
win.close()
if __name__ == '__main__':
main()
# button.py
# A simple Button widget.
from graphics import *
class Button:
"""A button is a labeled rectangle in a window.
It is activated or deactivated with the activate()
and deactivate() methods. The clicked(p) method
returns true if the button is active and p is inside it."""
def __init__(self, win, center, width, height, label):
""" Creates a rectangular button, eg:
qb = Button(myWin, Point(30,25), 20, 10, 'Quit') """
w,h = width/2.0, height/2.0
x,y = center.getX(), center.getY()
self.xmax, self.xmin = x+w, x-w
self.ymax, self.ymin = y+h, y-h
p1 = Point(self.xmin, self.ymin)
p2 = Point(self.xmax, self.ymax)
self.rect = Rectangle(p1,p2)
self.rect.setFill('lightgray')
self.rect.draw(win)
self.label = Text(center, label)
self.label.draw(win)
self.deactivate()
def clicked(self, p):
"RETURNS true if button active and p is inside"
return self.active and \
self.xmin <= p.getX() <= self.xmax and \
self.ymin <= p.getY() <= self.ymax
def getLabel(self):
"RETURNS the label string of this button."
return self.label.getText()
def activate(self):
"Sets this button to 'active'."
self.label.setFill('black')
self.rect.setWidth(2)
self.active = 1
def deactivate(self):
"Sets this button to 'inactive'."
self.label.setFill('darkgrey')
self.rect.setWidth(1)
self.active = 0
第四题