Creating A Python Rectangle Object Class That Can Print The Corner Coordinates
I am new to python. I need to create a python Rectangle object class that when called upon one can print the coordinates of the corners as well as have the area and perimeter. I am
Solution 1:
try this:
def__repr__(self):
return'tL = '+str(self.tL) + ', tR ='+ str(self.tR)+', bL ='+ str(self.bL) + ', bR =' +str(self.bR)
notes:
- make only one
return
statement execute in a function, in your code your function only returns self.bT (the last). - In the provided code
def __repr__(self)
is not indented. - you don't need 4 points to define a rectangle.
- your Rectangle corners shouldn't just be integers, they have to be sequences of two coordinates (x, y) for instance (3, 7) is a point, implement a point as a 2 integers tuple or list.
edit:
as the OP asked, here's how to change your __init__
method to work with cartesian coordinates:
classRectangle:
def__init__(self, tL, bR): #tL and bR should be passed as tuples
self.tL = tL
self.tR = (bR[0], tL[1]) #access tuple elements with tuple[index]
self.bL = (bR[1], tL[0])
self.bR = bR
self.width = bR[0]- tL[0]
self.height = bR[1] - tL[1]
defarea(self):
#get area#...defperim(self):
#get perim#...
r1 = Rectangle((5,5), (30, 20))
print r1.tL #output (5, 5)print r1.tR #output (30, 5)print r1.width #output 25print r1.area() #output 375
of course you can create a Point class
instead of that, and then you pass two Point
s to __init__
to define the rectangle.
I hope that helped you!
Solution 2:
First of all, functions cannot have more than one return statement.
Also, def __repr__(self):
is not correctly indented (it belongs to the Rectangle class).
You might prefer __str__
over __repr__
, see https://docs.python.org/2/reference/datamodel.html#object.repr for more details.
classRectangle:
def__init__(self, topLeft, topRight, bottomLeft, bottomRight):
self.tL = topLeft
self.tR = topRight
self.bL = bottomLeft
self.bR = bottomRight
defperim(self):
return (2 * (self.tL + self.tR)) + (2 * (self.bL + self.bR))
defarea(self):
return (self.tL + self.tR) * (self.bL + self.bR)
defposition(self):
return (self.tL, self.tR, self.bL, self.bR)
def__str__(self):
return"Rectangle(%s, %s, %s, %s)" % (self.tL, self.tR, self.bL, self.bR)
r1 = Rectangle (5, 5, 10, 10)
print r1
print"Perimeter: %s" % r1.perim()
print"Area: %s" % r1.area()
print"Position: (%s, %s, %s, %s)" % r1.position()
Post a Comment for "Creating A Python Rectangle Object Class That Can Print The Corner Coordinates"