【问题标题】:Python - calling on method in Point to check if Point is in RectanglePython - 调用 Point 中的方法以检查 Point 是否在 Rectangle 中
【发布时间】:2016-10-26 22:16:38
【问题描述】:

我正在学习 Python 中的类和方法,并且正在做“如何像计算机科学家一样思考”中的矩形/点练习。我进行了研究,但没有遇到与我遇到的相同问题的人。 我在 Rectangle 类中调用 self.width 和 self.height 时遇到问题。奇怪的是,在我编写的其他方法中调用它没有问题。当我调试时,它显示我的宽度和高度的实例什么都没有,现在我在我的最后手段 - 在这里!

这是我正在使用的代码:

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'''

【问题讨论】:

  • 在您的 contains 方法中,您实际上并没有使用 posn 参数。您需要针对矩形边界测试posn
  • @JETM a > a >= a 在 Python 中有效,但在其他语言中大多无效。
  • @DKrueger 我没有将它作为类 Point(3,3) 传递给矩形“r”吗?所以我在 print(r.contains(Point(3,3))) 中调用它时传递的点是 (3,3),矩形的大小是域 [0 10),范围是 [0, 5 ) 在我原来的矩形中 r = Rectangle(Point(0, 0), 10, 5)?
  • @ChrisAvina 是的,您正在传递它,但您从未在方法中使用它。该方法中没有实际使用的posn 的位置。也许你打算使用posn.x而不是self.corner.xy也一样)?

标签: python class methods rectangles


【解决方案1】:
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

contains 方法的作用是:

1) 检查给定点的x位置是否小于矩形的宽度并且大于或等于矩形的角的x位置:

self.width > point.x >= self.corner.x

2) 然后对 y 和高度做同样的事情:

self.height > point.y >= self.corner.y

3) 放在一起看起来像:

def contains(self, point):
    return self.width > point.x >= self.corner.x and self.height > point.y >= self.corner.y

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 2016-07-02
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2022-07-26
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多