類:求經常使用幾何形狀的周長與面積

# 定義一個抽象類,用來求經常使用幾何形狀的周長與面積,要求相同的能夠重複使用。
# 考察:類的定義,__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

 測試用例及輸出結果:python

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)的形式來實現的;spa

3.python經過在類的內部定義函數,來講明方法;code

4.對象包括屬性和方法;對象

5.子類能夠直接使用父類的方法,而不用定義;blog

6.self能夠跨函數使用;繼承

相關文章
相關標籤/搜索