赞
踩
1 from math import sin, cos, radians 2 3 def main(): 4 angle = float(input("Enter the launch angle (in degrees): ")) 5 vel = float(input("Enter the initial velocity (in meters/sec): ")) 6 h0 = float(input("Enter the initial height (in meters): ")) 7 time = float(input( 8 "Enter the time interval between position calculations: ")) 9 # convert angle to radians 10 theta = radians(angle) 11 12 # set the initial position and velocities in x and y directions 13 xpos = 0 14 ypos = h0 15 xvel = vel * cos(theta) 16 yvel = vel * sin(theta) 17 18 # loop until the ball hits the ground 19 while ypos >= 0.0: 20 # calculate position and velocity in time seconds 21 xpos = xpos + time *xvel 22 yvel1 = yvel - time * 9.8 23 ypos = ypos + time * (yvel + yvel1) / 2.0 24 yvel = yvel1 25 26 print("\nDistance traveled: {0:0.1f} meters.".format(xpos))
1 # misdie.py 2 # Class definition for an n-sided die. 3 4 from random import randrange 5 6 class MSDie: 7 8 def __init__(self, sides): 9 self.sides = sides 10 self.value = 1 11 12 def roll(self): 13 self.value = randrange(1, self.sides+1) 14 15 def getValue(self): 16 return self.value 17 18 def setValue(self, value): 19 self.value = value
1 # cball3.py 2 from math import sin, cos, radians 3 4 class Projectile: 5 6 def __init__(self, angle, velocity, height): 7 self.xpos = 0.0 8 self.ypos = height 9 theta = radians(angle) 10 self.xvel = velocity * cos(theta) 11 self.yvel = velocity * sin(theta) 12 13 def update(self, time): 14 self.xpos = self.xpos + time * self.xvel 15 yvel1 = self.yvel - 9.8 * time 16 self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 17 self.yvel = yvel1 18 19 def getY(self): 20 return self.ypos 21 22 def getX(): 23 return self.xpos 24 25 def getInputs(): 26 a = float(input("Enter the launch angle (in degrees): ")) 27 v = float(input("Enter the initial velocity (in meters/sec): ")) 28 h = float(input("Enter the initial height (in meters): ")) 29 t = float(input( 30 "Enter the time interval between position calculations: ")) 31 return a,v,h,t 32 33 def main(): 34 angle, vel, h0, time = getInputs() 35 cball = Projectile(angle, vel, h0) 36 while cball.getY() >= 0: 37 cball.update(time) 38 print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))
1 # gpa.py 2 # Program to find student with highest GPA 3 4 class Student: 5 def __init__(self, name, hours, qpoints): 6 self.name = name 7 self.hours = float(hours) 8 self.qpoints = float(qpoints) 9 10 def getName(self): 11 return self.name 12 13 def getHours(self): 14 return self.hours 15 16 def getQPoints(self): 17 return self.qpoints 18 19 def gpa(self): 20 return self.qpoints/self.hours 21 22 def makeStudent(infoStr): 23 # infoStr is a tab-separated line: name hours qpoints 24 # returns a corresponding Student object 25 name, hours, qpoints = infoStr.split("\t") 26 return Student(name, hours, qpoints) 27 28 def main(): 29 # open the input file for reading 30 filename = input("Enter the name of the grade file: ") 31 infile = open(filename, 'r') 32 33 # set best to the record for the first student in the file 34 best = makeStudent(infile.readline()) 35 36 #process subsequent lines of the file 37 for line in infile: 38 # turn the line into a student record 39 s = makeStudent(line) 40 # if this student is best so far, remember it. 41 if s.gpa() > best.gpa(): 42 best = s 43 infile.close() 44 45 #print information about the best student 46 print("The best student is:", best.getName()) 47 print("hours:", best.getHours()) 48 print("GPA:",best.gpa()) 49 50 if __name__ = '__main__': 51 main()
如果你以交互方式测试多模块 Python 项目(很好的事,要做),则需要了解 Python 模块导入机制中的微妙之处。当 Python 首次导入一个给定的模块时,它将创建一个包含模块中定义的所有内容的模块对象(在技术上,这称为“命名空间”)。如果模块成功导入(没有语法错误),则后续导入不会重新加载该模块,只是创建对已有模块对象的更多引用。即使某个模块已被更改(其源文件被编辑),将其重新导入到正在进行的交互式会话中也不会得到更新的版本。
可以使用标准库中 imp 模块的函数 reload()来交互地替换模块对象(有关详细信息,可参阅 Python 文档)。但是通常这不会给你希望的结果。这是因为对于当前会话中已经引用的模块旧版本的对象,重新加载模块不会更改任何标识符的值。事实上,很容易创建一种情形,让旧版本和新版本的对象同时处于活动状态,这至少会令人困惑。
避免这种混乱的最简单的方法,是确保每次测试中涉及的任何模块被修改时,都开始新的交互式会话。这样就可以保证对使用的所有模块进行全新(更新)导入。如果你正在使用 IDLE,会注意到,当选择“run module”时,它负责让 shell 重新启动,替你做这件事。
1 # button.py 2 from graphics import * 3 4 class Button: 5 6 """A button is a labeled rectangle in a window. 7 It is activated or deactivated with the activate() 8 and deactivate() methods. The clicked(p) method 9 return true if the button is active and p is inside it.""" 10 11 def __init__(self, win, center, width, height, label): 12 """Creates a rectangular button, eg: 13 qb = Button(myWin, centerPoint, width, height, 'Quit')""" 14 15 w,h = width/2.0, height/2.0 16 x,y = center.getX(), center.getY() 17 self.xmax, self.xmin = x+w, x-w 18 self.ymax, self.ymin = y+h, y-h 19 p1 = Point(self.xmin, self.ymin) 20 p2 = Point(self.xmax, self.ymax) 21 self.rect = Rectangle(p1,p2) 22 self.rect.setFill('lightgray') 23 self.rect.draw(win) 24 self.label = Text(center, label) 25 self.label.draw(win) 26 self.deactivate() 27 28 def clicked(self, p): 29 "Return true if button active and p is inside" 30 return (self.active and 31 self.xmin <= p.getX() <= self.xmax and 32 self.ymin <= p.getY() <= self.ymax) 33 34 def getLabel(self): 35 "Return the label string of this button." 36 return self.label.getText() 37 38 def activate(self): 39 "Sets this button to 'active'." 40 self.label.setFill('black') 41 self.rect.setWidth(2) 42 self.active = True 43 44 def deactivate(self): 45 "Sets this button to 'deactivate'." 46 self.label.setFill('darkgrey') 47 self.rect.setWidth(1) 48 self.activate = False
1 # dieview.py 2 from graphics import * 3 class DieView: 4 """ DieView is a widget that displays a graphical representation 5 of a standard six-sided die.""" 6 7 def __init__(self, win ,center, size): 8 """Create a view of a die, e.g.: 9 d1 = DieView(mywin, Point(40,50), 20) 10 creates a die centered at (40,50) having sides 11 of length 20.""" 12 13 # first define some standard values 14 self.win = win # save this for drawing pips later 15 self.background = "white" # color of die face 16 self.foreground = "black" # color of the pips 17 self.psize = 0.1 * size # radius of each pip 18 hsize = size / 2.0 # half the size of the die 19 offset = 0.6 * hsize # distance from center to outer pips 20 21 # create a square for the face 22 cx, cy = center.getX(), center.getY() 23 p1 = Point(cx-hsize, cy-hsize) 24 p2 = Point(cx+hsize, cy+hsize) 25 rect = Rectangle(p1, p2) 26 rect.setFill(self.background) 27 28 # Create 7 circles for standard pip locations 29 self.pip1 = self.__makePip(cx-offset, cy-offset) 30 self.pip2 = self.__makePip(cx-offset, cy) 31 self.pip3 = self.__makePip(cx-offset, cy+offset) 32 self.pip4 = self.__makePip(cx, cy) 33 self.pip5 = self.__makePip(cx+offset, cy-offset) 34 self.pip6 = self.__makePip(cx+offset, cy) 35 self.pip7 = self.__makePip(cx+offset, cy+offste) 36 37 # Draw an initial value 38 self.setValue(1) 39 40 def __makePip(self, x, y): 41 " Internal helper method to draw a pip at (x,y)" 42 pip = Circle(Point(x,y), self.psize) 43 pip.setFill(self.background) 44 pip.setOutline(self.background) 45 pip.draw(self.win) 46 return pip 47 48 def setValue(self, value): 49 "Set this die to display value." 50 # turn all pips off 51 self.pip1.setFill(self.background) 52 self.pip2.setFill(self.background) 53 self.pip3.setFill(self.background) 54 self.pip4.setFill(self.background) 55 self.pip5.setFill(self.background) 56 self.pip6.setFill(self.background) 57 self.pip7.setFill(self.background) 58 59 # turn correct pips on 60 if value == 1: 61 self.pip4.setFill(self.foreground) 62 elif value == 2: 63 self.pip1.setFill(self.foreground) 64 self.pip7.setFill(self.foreground) 65 elif value == 3: 66 self.pip1.setFill(self.foreground) 67 self.pip7.setFill(self.foreground) 68 self.pip4.setFill(self.foreground) 69 elif value == 4: 70 self.pip1.setFill(self.foreground) 71 self.pip3.setFill(self.foreground) 72 self.pip5.setFill(self.foreground) 73 self.pip7.setFill(self.foreground) 74 elif value == 5: 75 self.pip1.setFill(self.foreground) 76 self.pip3.setFill(self.foreground) 77 self.pip4.setFill(self.foreground) 78 self.pip5.setFill(self.foreground) 79 self.pip7.setFill(self.foreground) 80 else: 81 self.pip1.setFill(self.foreground) 82 self.pip2.setFill(self.foreground) 83 self.pip3.setFill(self.foreground) 84 self.pip5.setFill(self.foreground) 85 self.pip6.setFill(self.foreground) 86 self.pip7.setFill(self.foreground)
1 # roller.py 2 # Graphics program to roll a pair of dice.Uses custom widgets 3 # Button and DieView 4 5 from random import randrange 6 from graphics import GraphWin, Point 7 from button import Button 8 from dieview import DieView 9 10 def main(): 11 # create the application window 12 win = GraphWin("Dice Roller") 13 win.setCoords(0, 0, 10, 10) 14 win.setBackground("green2") 15 16 # Draw the interface widgets 17 die1 = DieView(win, Point(3,7), 2) 18 die2 = DieView(win, Point(7,7), 2) 19 rollButton = Button(win, Point(5,4.5), 6, 1, "Roll Dice") 20 rollButton.activate() 21 quitButton = Button(win, Point(5,1), 2, 1, "Quit") 22 23 # Event loop 24 pt = win.getMouse() 25 while not quitButton.clicked(pt): 26 if rollButton.clicked(pt): 27 value1 = randrange(1,7) 28 die1.setValue(value1) 29 value2 = randrange(1,7) 30 die2.setValue(value2) 31 quitButton.activate() 32 pt = win.getMouse() 33 34 # close up shop 35 win.close() 36 37 main()
1 # file: animation.py 2 3 def main(): 4 5 # create animation window 6 win = GraphWin("Projectile Animation", 640, 480, autoflush=Flase) 7 win.setCoords(-10, -10, 210, 155) 8 Line(Point(-10,0), Point(210, 0)).draw(win) 9 for x in range(0, 210, 50): 10 Text(Point(x,-5), str(x)).draw(win) 11 Line(Point(x,0), Point(x,2)).draw(win) 12 13 # even loop, each time through fires a single shot 14 angle,vel, height = 45.0, 40.0, 2.0 15 while True: 16 # interact with the user 17 inputwin = InputDialog(angle, vel, height) 18 choice = inputwin.interact() 19 inputwin.close() 20 21 if choice == "Quit": # loop exit 22 break 23 24 # create a shot and track until it hits ground or leaves window 25 angle, vel, height = inputwin.getValues() 26 shot = ShotTracker(win, angle, vel, height) 27 while 0 <= shot.getY() and -10 < shot.getX() <= 210: 28 shot.update(1/50) 29 update(50) 30 win.close()
10.8小结
本章展示了如何使用类定义。以下是一些要点的总结。
1.对象包括相关数据的集合以及操纵该数据的一组操作。数据存储在实例变量中并通过方法进行操作。
2.每个对象都是某个类的一个实例。类定义确定了对象的属性是什么。程序员可以通过编写合适的类定义来创建新类型的对象。
3.Python 类定义是一组函数定义。这些函数实现了类的方法。每个方法定义的第一个参数都是特殊的,称为 self。self 的实际参数是应用该方法的对象。利用点表示法,self 参数可用于访问对象的属性。
4.特殊方法__init__是类的构造方法。它的工作是初始化对象的实例变量。定义新对象(通过类)可以让单个变量保存一组相关数据,从而简化程序的结构。对象对于建模真实世界的实体是有用的。这些实体可能有复杂的行为,记录在方法的算法(例如抛体),或者它们可能只是关于某个人(例如学生记录)的相关信息的集合。
5.正确设计的类提供了封装。对象的内部细节隐藏在类定义之内,这样程序的其他部分不需要知道对象的实现方式。这种关注点分离是 Python 中的编程惯例,对象的实例变量只能通过类的接口方法进行访问或修改。
6.大多数 GUI 系统是用面向对象的方法构建的。我们可以通过定义合适的类来构建创新的 GUI 控件。GUI 控件可以构建自定义的对话框,用于用户交互。
10.9 练习
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。