您所在的位置:小祥子 » 编程 » Python » 正文

Python学习 —— 阶段综合练习二

时间:2015-04-19 编辑:feesland 来源:本站整理

  综合之前的类的学习,做以下实例练习:(建议先不要看代码,自己先试着写;代码仅供参考,有多种实现方法)

  1. Triangle  & Equilateral

    1). 创建class Triangle 表示三角形,包含三个属性值:angle1、angle2、angle3;类方法 check_angles():若三个角相加 == 180,return True;若不是,return False

 class Triangle(object):
     def __init__(self,angle1,angle2,angle3):
         self.angle1 = angle1
         self.angle2 = angle2
         self.angle3 = angle3
 
     def checkAngles(self):
         if (self.angle1+self.angle2+self.angle3) == 180 :
             return True
         else:
             return False
 
 t1 = Triangle(40,50,90)
 print(t1.angle1,t1.angle2,t1.angle3)
 print(t1.checkAngles())
 t2 = Triangle(40,50,91)
 print(t2.checkAngles())
Triangle

    2). 创建class Equilateral 继承上例1的Triangle,表示等边三角形,同Triangle不同点在于,其属性值的三个角均为60;而对应的 check_angles() 自然始终返回True

 class Equilateral(Triangle):
     def __init__(self,angle1=60,angle2=60,angle3=60):
         self.angle1 = angle1
         self.angle2 = angle2
         self.angle3 = angle3
         
 t3 = Equilateral()
 print(t3.angle1,t3.angle2,t3.angle3)
 print(t3.checkAngles())
Equilateral 1

   如上示例代码可满足条件,但更好的做法是调用父类构造函数,重写check_angles() 使其始终返回 True,参见代码如下

 class Equilateral(Triangle):
     def __init__(self,angle1=60,angle2=60,angle3=60):
         Triangle.__init__(self,angle1,angle2,angle3)
     
     def checkAngles(self):
         return True
 
 t3 = Equilateral()
 print(t3.angle1,t3.angle2,t3.angle3)
 print(t3.checkAngles())
Equilateral 2

  2.  Car & ElectricCar

    1). 创建class Car 成员变量condition = "new",包含三个构造属性:model,color,mpg;

      类方法 displayCar() print 拼接的字符串 This is a {color} {model} car with {mpg} MPG. 如 "This is a blue Xmodel car with 40 MPG." 注意空格拼接
      类方法 driveCar() 改变成员变量condition = "used"

 class Car(object):
     condition = "new"
     def __init__(self,model,color,mpg):
         self.model = model
         self.color = color
         self.mpg = mpg
     
     def displayCar(self):
         print ("This is a {s.color} {s.model} car with {s.mpg} MPG.".format(s=self))
         
     def driveCar(self):
         self.condition = "used"
 
 car1 = Car("DeLorean", "silver", 88)
 car1.displayCar()
 print(Car.condition)
 print(car1.condition)
 car1.driveCar()
 print(car1.condition)
Car
关键词:学习