在Python中计算给定另一个类的对象的周长

2024-03-28 15:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如果没有矩形类中保存的x坐标和y坐标,如何计算名为“矩形”的对象的周长。你知道吗

class Point:

    def __init__(self, xcoord=0, ycoord=0):
        self.x = xcoord
        self.y = ycoord

    def setx(self, xcoord):
        self.x = xcoord

    def sety(self, ycoord):
        self.y = ycoord

    def get(self):
        return (self.x, self.y)

    def move(self, dx, dy):
        self.x += dx
        self.y += dy

class Rectangle:

    def __init__(self, bottom_left, top_right, colour):
        self.bottom_left = bottom_left
        self.top_right = top_right
        self.colour = colour

    def get_colour(self):
        return self.colour

    def get_bottom_left(self):
        return self.bottom_left

    def get_top_right(self):
        return self.top_right

    def reset_colour(self, colour):
        self.colour = colour

    def move(self,dx,dy):
        Point.move(self.bottom_left,dx,dy)
        Point.move(self.top_right,dx,dy)

    def get_perimeter(self):

我在pythonshell中以以下格式调用函数

r1=Rectangle(Point(),Point(1,1),'red')
r1.get_perimeter()

Tags: selfrightgetmovereturntopdefleft
1条回答
网友
1楼 · 发布于 2024-03-28 15:45:49

这是比Python更基本的几何。你知道吗

因为您只提供左下角和右上角的点,所以我假设矩形的边与x/y轴平行。在这种情况下:

def get_perimeter(self):
    return 2*(abs(self.top_right.x-self.bottom_left.x)+abs(self.bottom_left.y-self.top_right.y))

我对abs函数进行了很好的度量,因为left&right,top&bottom并不以坐标系的方向为前提。你知道吗

注意:您在Rectangle类中有2个定义点“saved”(可访问)的^{eem>xy,不是直接作为直接成员,而是作为成员的成员。你知道吗

相关问题 更多 >