I have a point and rectangle class. I am trying to write a function in the rectangle class that will check if the point is in the rectangle, but I am getting syntax errors.
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({},{})".format(self.x, self.y)
class Rectangle(object):
def __init__(self, posn, w, h):
self.corner = posn
self.width = w
self.height = h
def __str__(self):
return "({0},{1},{2})".format(self.corner, self.width, self.height)
def contains(self):
if self.x < self.width and self.y < self.height:
return True
else:
return False
Your contains
method doesn't take a point as an argument, only self
(which is the rectangle you're calling the method on). You need to add a parameter, then use it when looking up the point's info.
You probably also need to check all boundaries of the rectangle, so there will be four comparisons. You can simplify the comparisons a bit by using Python's operator chaining (a < b < c
is equivalent to a < b and b < c
).
Furthermore, there's no need for if
statements, you can just return the Boolean result of your comparisons directly.
Here's code that I think should work for you, though I may not have correctly guessed at how you are treating the corner
value:
def contains(self, point):
return (self.corner.x <= point.x <= self.corner.x + self.width and
self.corner.y <= point.y <= self.corner.y + self.height)