# 定义一个抽象类,用来求常用几何形状的周长与面积,要求相同的可以重复使用。
# 考察:类的定义,__init__方法,类的成员方法,类的继承
# 形状有:正方形,圆,长方形
# 参考单词:Shape, square, Circle,rectangle
#!/usr/bin/env python # -*- coding: utf-8 -*- import math class Shape(object): #基类 def __init__(self,length,width,radius): if length == 0 or width == 0: raise ValueError() self.length = length self.width = width self.radius = radius def area(self): print u"求面积:" area = self.length * self.width return area def perimeter(self): print u"求周长:" perimeter = (self.length + self.width) *2 return perimeter class Square(Shape): "正方形" def __init__(self,length): super(Square, self).__init__(length,length,0) class Rectangle(Shape): "矩形" pass class Circle(): "圆" pi = 3.1415926 def __init__(self,radius): self.radius = radius def area(self): print u"求圆的面积:" return Circle.pi*self.radius*self.radius def perimeter(self): print u"求圆的周长:" return 2*Circle.pi*self.radius class Triangle(Shape): "等边三角形" def __init__(self,length): super(Triangle, self).__init__(length,length,0) def area(self): return super(Triangle, self).area()*(math.sqrt(3)/2) def perimeter(self): return super(Triangle, self).perimeter()-self.length
测试用例及输出结果:
if __name__ == "__main__": square = Square(5) print square.area() print square.perimeter() ret = Rectangle(6,4,0) print ret.area() print ret.perimeter() circle = Circle(3) print circle.area() print circle.perimeter() triangle = Triangle(4) print triangle.area() print triangle.perimeter()
总结:
1.类的名称用首字母大写的单词;
2.对属性的引用是通过“对象.属性”(object.attribute)的形式来实现的;
3.python通过在类的内部定义函数,来说明方法;
4.对象包括属性和方法;
5.子类可以直接使用父类的方法,而不用定义;
6.self可以跨函数使用;