这周上课又学回到了Python面向对象编程以及类的封装等,这里写个关于类的应用, 也不是很难,不过相对于基础来说以及够够了。
写一个类,通过这个工具类能够画一个长方形(用*画)工具类:
长方形类:
属性:
宽 private double width
高 private double height
面积private double area
周长private double perimeter
是不是空心 private boolean empty
方法:
通过边长计算面积
通过边长计算周长
获取一个长方形:宽度、高度、面积、周长、是否空心的方法(get方法)
修改一个长方形:宽度、高度、是否空心的方法(set方法)
绘制图形方法:通过属性判断是否空心,然后进行图形绘制
首先定义一个类,名称就简单明了地用长方形的缩写好了。
import math
Class Cfx():
要求里对属性的类型有要求,定义下属性,之后创建构造器,给属性赋初值。
Class Cfx():
__width = 0.0
__height = 0.0
__area = 0.0
__perimeter = 0.0
__empty = True
def __init__(self,width,height):
self.__width = width
self.__height = height
接下来是方法的创建,第一个方法要求计算长方形的面积,根据面积的定义可知area=width*height
def Area(self):
self.__area = self.__width*self.__height
return self.__area
第二个方法是求长方形的周长,定义可知perimeter=(width+height)*2
def Perimeter(self):
self.__perimeter = self.__width*2+self.__height*2
return self.__perimeter
第三个方法是获取长方形的属性,这里我通过属性值的配对来返回相对应的结果。要注意输出时都要转成string型,否则会报错。
def __get__(self,key):
if key =="width":
return "宽度:" + str(self.__width)
if key =="height":
return "\n高度:"+str(self.__height)
if key == "area":
return "\n面积:"+str(self.Area())
if key =="perimeter":
return "\n周长:"+str(self.Perimeter())
if key =="empty":
return "\n是否空心:"+str(self.__empty)
如果要返回所有属性,则用get_all方法。
def get_all(self):
return "宽度:" + str(self.__width)+"\n高度:"+str(self.__height)+"\n面积:"+str(self.Area())+ "\n周长:"+str(self.Perimeter())+"\n是否空心:"+str(self.__empty)
第四个方法是改变相应属性的值,这里也是通过属性名的配对来修改。
def __set__(self,key,value):
if key == "width":
self.__width = value
if key == "height":
self.__height = value
if key == "empty":
self.__empty = value
第五个方法是画出长方形,这里首先要注意长方形的长宽可能是小数,然后要判断是不是空心。
对于带小数的长方形,我考虑的是将一个*代表的大小改变来画图。
def Paint(self):
w = self.__width
h = self.__height
tempw = w - math.floor(w)
temph = h - math.floor(h)
if temph > 0 or tempw > 0:#小数部分
index = 0
while tempw * (10 ** index) < 1: #循环直到小数部分大于1为之,最终的index决定一个*代表的大小。
wi = index
index += 1
while temph * (10 ** index) < 1:
hi = index
index += 1
if wi >= hi: #比较长宽哪个的小数更小,选择小的来作为*所代表的大小
whi = wi
else:
whi = hi
standard = 10 ** (-whi)
print("每个*号代表单位长度%f" % standard) #图注
w = w * (10 ** whi)
h = h * (10 ** whi)
之后是判断是否空心以及画图,这里逻辑比较简单,就不详细解释了。
if self.__empty == True:
i = 1
while i<=h:
if i > 1 and i < h:
j = 1
while j <= w:
if j == 1 or j==w:
print("*", end="")
if j>1 and j<w:
print(end=" ")
j += 1
print()
if i == 1 or i == h:
j = 1
while j <= w:
print("*", end="")
j += 1
print()
i += 1
else:
i = 1
while i<=h:
j = 1
while j<=w:
print("*",end="")
j += 1
i += 1
print()
最后是对这个类的测试,测试数据如下:
图太长了放不下,不过没什么问题。