Python类方法到ID的交点Point w矩形uwing set()和Intersection()不起作用

时间:2014-11-09 13:47:02

标签: python

..尝试在我的Point Class中定义一个方法,该方法使用基于类型的dispatch检查内部或边界上与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)

1 个答案:

答案 0 :(得分:0)

它是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

您可以简化Rectangle中的赋值:

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)

您也可以使用set literals:

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