简体   繁体   中英

How to find the area and perimter of a rectangle that has two points defined?

I have a Point class and Rectangle class set up, here is the code for that:

import math

class Point:
    """A point in two-dimensional space."""

    def __init__(self, x: float = 0.0, y: float = 0.0)->None:               
        self.x = x
        self.y = y    


    def moveIt(self, dx: float, dy: float)-> None:
        self.x = self.x + dx
        self.y = self.y + dy    

    def distance(self, otherPoint: float): 
        if isinstance(otherPoint, Point):
            x1 = self.x
            y1 = self.y
            x2 = otherPoint.x
            y2 = otherPoint.y

            return ( (x1 - x2)**2 + (y1 - y2)**2 )**0.5    


class Rectangle:
    def __init__(self, topLeft = Point(0,0), bottomRight = Point(1,1)):
        self.topLeft = topLeft
        self.bottomRight = bottomRight

The two points are the top left and the bottom right for the rectangle. How could I find the area and perimeter of this rectangle from two points? Would appreciate any and all help!

We can access the x and y values of each point and calculate the height and width, from there we can create methods that calculate area and perimeter

class Rectangle():
    def __init__(self, topLeft = Point(0,0), bottomRight = Point(1,1)):
        self.topLeft = topLeft
        self.bottomRight = bottomRight
        self.height = topLeft.y - bottomRight.y
        self.width = bottomRight.x - topLeft.x
        self.perimeter = (self.height + self.width) * 2
        self.area = self.height * self.width

rect = Rectangle(Point(3,10),Point(4,8))
print(rect.height)
print(rect.width)
print(rect.perimeter)
print(rect.area)
 chrx@chrx:~/python/stackoverflow/9.24$ python3.7 rect.py 2 1 6 2

Or using methods

class Rectangle():
    def __init__(self, topLeft = Point(0,0), bottomRight = Point(1,1)):
        self.topLeft = topLeft
        self.bottomRight = bottomRight
        self.height = topLeft.y - bottomRight.y
        self.width = bottomRight.x - topLeft.x

    def make_perimeter(self):
        self.perimeter = (self.height + self.width) * 2
        return self.perimeter

    def make_area(self):
        self.area = self.height * self.width
        return self.area

rect = Rectangle(Point(3,10),Point(4,8))
print(rect.height)
print(rect.width)
print(rect.make_perimeter())
print(rect.make_area())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM