题目
需求:设计两个类:
一个点Point类,属性包括 x 和 y 坐标。
一个矩形Rectangle类,属性有左上角(top_left)和 右下角(bottom_right)的坐标。
方法:1.计算矩形的面积(get_area);2.判断点是否在矩形内(is_inside)。
主程序:
实例化一个点对象,一个正方形对象,输出矩形的面积,输出点是否在矩形内。
代码
# @Time: 2021/10/15 13:21
# @Auth: 君若(QQ1813774883)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "点Point的坐标为({},{})".format(self.x, self.y)
class Rectangle:
def __init__(self, top_left_x, top_left_y, bottom_right_x, bottom_right_y):
self.top_left_x = top_left_x
self.top_left_y = top_left_y
self.bottom_right_x = bottom_right_x
self.bottom_right_y = bottom_right_y
self.chang = 0
self.kuan = 0
def __str__(self):
return "矩形Rectangle的左上角坐标为({},{})右下角坐标为({},{})".format(self.top_left_x, self.top_left_y, self.bottom_right_x,
self.bottom_right_y)
def is_hefa(self):
self.chang = round(self.bottom_right_x - self.top_left_x, 2)
self.kuan = round(self.top_left_y - self.bottom_right_y, 2)
if self.chang <= 0 or self.kuan <= 0: # 矩形左上角和右下角(x1,y2)和(x2,y2) 应该满足 x1<x2 y1>y2 ,才是合法的。
return 0
else:
return 1
def get_area(self):
return "矩形:\n 长:{}\n 宽:{}\n 面积:{}".format(self.chang, self.kuan, self.chang * self.kuan)
def is_inside(self, point):
if self.top_left_x < point.x < self.bottom_right_x and self.top_left_y > point.y > self.bottom_right_y:
return "点在矩形内"
else:
return "点不在矩形内"
point = Point(2, 3)
rectangle = Rectangle(1, 4, 4, 1)
print(point)
print(rectangle)
if rectangle.is_hefa() == 0:
print("矩形数据不合法;")
else:
print(rectangle.get_area())
print(rectangle.is_inside(point))
版权属于:君若(QQ:1813774883)
本文链接:https://jrboy.cn/610.html
转载时须注明出处及本声明
1 条评论
滴!学生卡!打卡时间:下午9:14:57,请上车的乘客系好安全带~