一、面向过程,是按照问题解决步骤,一步一步的进行,思路比较简单,但是不易维护,面向对象编程是将问题分块,各个模块搭建最后的总的解决方案
1、铅球问题的面向对象编程
1 from math import sin, cos, radians 2 #创建类 3 class Projectile: 4 def __init__(self, angle, velocity, height): 5 6 #创建状态,根据给定的发射角度、初始速度和位置创建一个投射体对象 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 #创建类的方法 14 def update(self, time): 15 #更新投射体的状态 16 self.xpos = self.xpos + time * self.xvel 17 yvell = self.yvel - 9.8 * time 18 self.ypos = self.ypos + time * (self.yvel + yvell) / 2.0 19 self.yvel = yvell 20 21 def getY(self): 22 #返回投射体的角度 23 return self.ypos 24 25 def getX(self): 26 #返回投射体的距离 27 return self.xpos
调用类
1 from Projectile import * 2 3 def getInputs(): 4 a = eval(input("Enter the launch angle (in degrees):")) 5 v = eval(input("Enter the initial velocity (in meters/sec):")) 6 h = eval(input("Enter the initial height (in meters):")) 7 t = eval(input("Enter the time interval: ")) 8 return a,v,h,t 9 10 def main(): 11 angle,vel,h0,time = getInputs()#输入参数 12 shot = Projectile(angle,vel,h0)#调用类,注意只用三个参数 13 while shot.getY() >=0: 14 shot.update(time) 15 print(" Distance traveled:{0:0.1f}meters.".format(shot.getX())) 16 17 if __name__ == "__main__": 18 main()
2、GPA
1 # 找到GPA最高的学生 2 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 #定义方法 11 def getName(self): 12 return self.name 13 14 def getHours(self): 15 return self.hours 16 17 def getQPoints(self): 18 return self.qpoints 19 20 def gpa(self): 21 return self.qpoints/self.hours 22 23 #定义函数,获取每一行数据 24 def makeStudent(infoStr): 25 name, hours, qpoints = infoStr.split(" ") 26 return Student(name, hours, qpoints) 27 28 def main(): 29 # 打开输入文件 30 filename = input("Enter name the grade file: ") 31 infile = open(filename, 'r') 32 # 设置文件中第一个学生的记录为best 33 best = makeStudent(infile.readline()) 34 35 # 处理文件剩余行数据 36 for line in infile: 37 # 将每一行数据转换为一个记录 38 s = makeStudent(line) 39 # 如果该学生是目前GPA最高的,则记录下来 40 if s.gpa() > best.gpa(): 41 best = s 42 infile.close() 43 44 # 打印GPA成绩最高的学生信息 45 print("The best student is:", best.getName()) 46 print("hours:", best.getHours()) 47 print("GPA:", best.gpa()) 48 49 if __name__ == '__main__': 50 main()