繁体   English   中英

Python - 在 Point 中调用方法来检查 Point 是否在矩形中

[英]Python - calling on method in Point to check if Point is in Rectangle

我正在学习 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'''
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM