Python-100-Days/Day01-15/code/Day08/rect.py

44 lines
884 B
Python
Raw Permalink Normal View History

2018-04-27 00:00:22 +08:00
"""
定义和使用矩形类
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
class Rect(object):
2019-05-03 21:17:36 +08:00
"""矩形类"""
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def __init__(self, width=0, height=0):
2019-05-03 21:53:37 +08:00
"""初始化方法"""
2019-05-03 21:17:36 +08:00
self.__width = width
self.__height = height
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def perimeter(self):
"""计算周长"""
return (self.__width + self.__height) * 2
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def area(self):
"""计算面积"""
return self.__width * self.__height
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def __str__(self):
"""矩形对象的字符串表达式"""
return '矩形[%f,%f]' % (self.__width, self.__height)
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def __del__(self):
"""析构器"""
print('销毁矩形对象')
2018-04-27 00:00:22 +08:00
if __name__ == '__main__':
2019-05-03 21:17:36 +08:00
rect1 = Rect()
print(rect1)
print(rect1.perimeter())
print(rect1.area())
rect2 = Rect(3.5, 4.5)
print(rect2)
print(rect2.perimeter())
print(rect2.area())