《 Python程序设计(第3版)》[美] 约翰·策勒(John Zelle) 第 10 章 答案

True/False

  1. True
  2. False
  3. False
  4. False (it may have more)
  5. False
  6. True
  7. False
  8. False
  9. False
  10. True

Multiple Choice

  1. b
  2. a
  3. d
  4. b
  5. c
  6. d
  7. c
  8. a
  9. c
  10. c

Discussion

  1. 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.
  2.  
    1. 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.
    2. 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.
    3. A constructor is the method that constructs an object. In Python, it is a method named __init__
    4. An accessor is a method that returns the value of an isntance variable, for example:
      def getValue(self):
          return self.value
    5. A mutator is a method that changes the value of one or more instance variables.
      def roll(self):
          self.value = randrange(1,7)
  3. 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

第四题

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值