I'm learning classes and methods in Python and I'm doing the Rectangle/Point exercise in 'How to Think Like a Computer Scientist'. I've researched, but have not come across someone the same problem that I'm running into. I'm having a problem calling on self.width and self.height in my Rectangle Class. What's strange is that I have no problem calling on it in my other methods that I wrote. When I debug, it shows the instance of my width and height as nothing and now I'm at my last resort - here!
Here is the code I'm using:
class Point:
"""Sets up a class point. If user doesn't supply args it starts at
0,0)"""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
class Rectangle:
'''A class to create rectangle objects '''
def __init__(self, posn, w, h):
self.corner = posn '''position of rectangle as tuple (Point Class)'''
self.width = w '''Sets self.width as w'''
self.height = h '''Sets self.height as h'''
'''Added grow and move methods to display how I'm calling
self.width/height and self.corner.x/y. These both work when I call them'''
def grow(self, delta_width, delta_height):
'''Grow or shrink object by deltas'''
self.width += delta_width
self.height += delta_height
def move(self, dx, dy):
'''Move this object by the deltas'''
self.corner.x += dx
self.corner.y += dy
'''This is where I'm having the problem. '''
def contains(self, posn):
return (self.width > self.corner.x >= 0
and self.height > self.corner.y >= 0)
r = Rectangle(Point(0, 0), 10, 5)
print(r.contains(Point(0,0))) '''Should return True'''
print(r.contains(Point(3,3))) '''Should return True'''
print(r.contains(Point(3, 7))) '''Should return False, but returns True'''
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Rectangle:
def __init__(self, posn, w, h):
self.corner = posn
self.width = w
self.height = h
def contains(self, point):
return self.width > point.x >= self.corner.x and self.height > point.y >= self.corner.y
What the contains
method is doing is:
1) Checking if the given point's x position is less than the rectangle's width and larger than or equal to the rectangle's corner's x position:
self.width > point.x >= self.corner.x
2) And then doing the same thing for y and the height:
self.height > point.y >= self.corner.y
3) Put together it looks like:
def contains(self, point):
return self.width > point.x >= self.corner.x and self.height > point.y >= self.corner.y
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.