Garret Ulrich - 2 years ago 87
Python Question

# Calculating the perimeter of my object given another class in Python

I was wondering how I can calculate the perimeter of my object called 'Rectangle' if I do not have the x-coordinates and y-coordinates saved in the Rectangle class.

``````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):
``````

I am calling the function in python shell in the following format

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

That's more basic geometry than Python.

Since you only provide bottom left and top right points I'm assuming that the rectangle has sides parallel to x/y axis. In that case:

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

I've put the `abs` function for good measure because left & right, top & bottom doesn't presuppose of the orientation of the coordinate system.

Note: you have `x` and `y` of the 2 defining points "saved" (accessible) in your `Rectangle` class, not directly as a direct member, but as a member of a member.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download