Python类方法用于标识点w矩形的交点,该交点在set()和intersection()不起作用的情况下

Python类方法用于标识点w矩形的交点,该交点在set()和intersection()不起作用的情况下,python,Python,…尝试在我的Point类中定义一个方法,该方法使用基于类型的分派检查与内部或边界上矩形类对象的交互。我尝试了下面的代码,但结果是:AttributeError:“set”对象没有属性“intersects” 此外,寻求一种方法来清楚地设置边界与内部的交叉点。请告知 class Point(object): def __init__(self, x, y, height=0): self.x = float(x) self.y = float(y)

…尝试在我的Point类中定义一个方法,该方法使用基于类型的分派检查与内部或边界上矩形类对象的交互。我尝试了下面的代码,但结果是:AttributeError:“set”对象没有属性“intersects”

此外,寻求一种方法来清楚地设置边界与内部的交叉点。请告知

class Point(object):
    def __init__(self, x, y, height=0):
        self.x = float(x)
        self.y = float(y)
        self.height = float(height)

def intersects(self, other):
        if isinstance(other, Point):
            s1=set([self.x, self.y])
            s2=set([other.x, other.y])
            if s1.intersection(s2):
                return True
            else:
                return False
        elif isinstance(other, Rectangle):
             s1=set([self.x, self.y])
             s2=set(other.pt_ll, other.pt_ur)
             if s1.intersection(s2):
                return True
             else:
                return False

class Rectangle(object):    
    def __init__(self, pt_ll, pt_ur):
        """Constructor. 
        Takes the lower left and upper right point defining the Rectangle.
        """
        self.ll = pt_ll        
        self.lr = Point(pt_ur.x, pt_ll.y)
        self.ur = pt_ur
        self.ul = Point(pt_ll.x, pt_ur.y)
以下是我的发言:

pt0 = (.5, .5)
r=Rectangle(Point(0, 0),Point(10, 10))

s1 = set([pt0])
s2 = set([r])
print s1.intersects(s2)
它将是交点s1.intersections2,您使用的是集合而不是点对象:

s1 = set([pt0]) # <- creates a python set 
因此,使用您的示例,您需要使用矩形类的属性访问点对象:

也可以仅使用集合文字:

s1 = {self.x, self.y}
s2 = {other.x, other.y}

我明白了。我只是不清楚:pt0=.5,.5r=矩形点0,0,点10,10 printr.lr.intersectsr.ul。。pt0不应该在打印stmt中吗。但是如何同时引用r attributeST0=Point.5、.5 printr.lr.intersectspt0您需要使用点对象来访问点方法,不清楚您到底想做什么,但访问点对象肯定是其中的一部分
r = Rectangle(Point(0, 0),Point(10, 10))
print(r.lr.intersects(r.ul)) # <- the Rectangle attributes  lr and ul are Point objects because you passed in Point's when you initialised the instance r
class Rectangle(object):
    def __init__(self, pt_ll, pt_ur):
        """Constructor.
        Takes the lower left and upper right point defining the Rectangle.
        """
        self.lr = Point(pt_ur.x, pt_ll.y)
        self.ul = Point(pt_ll.x, pt_ur.y)
s1 = {self.x, self.y}
s2 = {other.x, other.y}