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 having issues when I try to run my code that says:
<__main__.Rectangle instance at 0x02F20030>
I was told to add the __str__
as well but then I get:
TypeError: __str__ returned non-string (type int)
Any help would be appreciated, thanks!
class Rectangle:
def __init__(self, topLeft, topRight, bottomLeft, bottomRight):
self.tL = topLeft
self.tR = topRight
self.bL = bottomLeft
self.bR = bottomRight
def perim(self):
return (2 * (self.tL + self.tR)) + (2 * (self.bL + self.bR))
def area(self):
return (self.tL + self.tR) * (self.bL + self.bR)
def position(self):
return self.tL
return self.tR
return self.bL
return self.bR
def __repr__(self):
return self.tL
return self.tR
return self.bL
return self.bT
r1 = Rectangle (5, 5, 10, 10)
print r1
try this:
def __repr__(self):
return 'tL = '+str(self.tL) + ', tR ='+ str(self.tR)+', bL ='+ str(self.bL) + ', bR =' +str(self.bR)
notes:
return
statement execute in a function, in your code your function only returns self.bT (the last).def __repr__(self)
is not indented.edit:
as the OP asked, here's how to change your __init__
method to work with cartesian coordinates:
class Rectangle:
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]
def area(self):
#get area
#...
def perim(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 25
print 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!