用于识别点w矩形uwing集()和intersection()的交集的Python类方法不起作用



。。尝试在我的Point类中定义一个方法,该方法使用基于类型的分派来检查内部或边界上与Rectangle类的对象的交互。我尝试了下面的代码,但得到了: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)

它将是intersection() s1.intersection(s2),您使用的是set而不是Point对象:

s1 = set([pt0]) # <- creates a python set 

要使用intersects方法,您需要Point对象:

p = Point(3,5) # <- creates a Point object that has intersects method
p2 = Point(3,5)
print(p.intersects(p2))

因此,使用您的示例,您需要使用Rectangle类的属性来访问Point对象:

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}

最新更新