我正在构建一个Rectangle类,以查看两个矩形是否在拐角处接触。这是openbookproject针对python第16章的最后一个练习。 http://openbookproject.net/thinkcs/python/english3e/classes_and_objects_II.html
我遇到的问题是我已经定义了一个函数same_coordinates 然后使用该函数定义一个方法corner_touching,但是当我这样做时,我得到一个NameError:名称'same_coordinates'未定义,我不确定为什么。
class Rectangle:
"A class to manufacture Rectangle objects"
...
def same_coordinates(P1,P2):
return P1.x == P2.x and P1.y == P2.y
def corner_touching(self,r2):
r1bl = cao.Point(self.corner.x,self.corner.y)
r1br = cao.Point(self.corner.x+self.width,self.corner.y)
r1tr = cao.Point(self.corner.x+self.width,self.corner.y +
self.height)
r1tl = cao.Point(self.corner.x,self.corner.y + self.height)
r2bl = cao.Point(r2.corner.x,r2.corner.y)
r2br = cao.Point(r2.corner.x+r2.width,r2.corner.y)
r2tr = cao.Point(r2.corner.x+r2.width,r2.corner.y + r2.height)
r2tl = cao.Point(r2.corner.x,r2.corner.y + r2.height)
return same_coordinates(r1bl,r2tr) or same_coordinates(r1tl,r2br) or \
same_coordinates(r1tr,r2bl) or same_coordinates(r1br,r2tl)
我已经使用“ ...”来表示init和其他运行良好的方法。使用两个矩形时出现的错误是:
发生异常:NameError 名称'same_coordinates'未定义
这很有趣,因为我发誓我已经在corner_touching上方两行定义了它。任何帮助将不胜感激!!!
答案 0 :(得分:0)
如果方法same_coordinates
的交集如上所示,则这是一个类方法,您应该在一个对象上调用它。如果将此方法移出类,则应该可以使用。
答案 1 :(得分:0)
您可以尝试执行以下操作:
return self.same_coordinates(r1bl,r2tr) or self.same_coordinates(r1tl,r2br) or \
self.same_coordinates(r1tr,r2bl) or self.same_coordinates(r1br,r2tl)
问题是您在函数中具有自我。在该类中,使用self.FUNC进行调用。 我希望它能起作用!
答案 2 :(得分:0)
same_coordinates
是Rectangle
类的属性,而不是任何局部或全局范围内的变量。您需要通过Rectangle
或其实例之一来访问它。
def corner_touching(self,r2):
# ...
return self.same_coordinates(r1bl, r2tr) or \
self.same_coordinates(r1tl, r2br) or \
self.same_coordinates(r1tr, r2bl) or \
self.same_coordinates(r1br, r2tl)
由于是一个属性,因此也应将其声明为静态方法,因为它需要两个Point
实例(但没有Rectangle
实例)作为参数:
@staticmethod
def same_coordinates(P1,P2):
return P1.x == P2.x and P1.y == P2.y
或者,您可以将其定义为全局函数,在这种情况下,您无需更改corner_touching
:
def same_coordinates(P1, P2):
return P1.x == P2.x and P1.y == P2.y
class Rectangle:
"A class to manufacture Rectangle objects"
def corner_touching(self,r2):
# ...
return same_coordinates(r1bl, r2tr) or \
same_coordinates(r1tl, r2br) or \
same_coordinates(r1tr, r2bl) or \
same_coordinates(r1br, r2tl)
答案 3 :(得分:0)
使用__eq__
魔术方法。您要尝试做的正是__eq__
做的事。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p1 = Point(3, 4)
p2 = Point(4, 4)
p3 = Point(3, 4)
print(p1 == p2) # will print False
print(p1 == p3) # will print True