[英]Why am I getting a NameError when I've defined my variable name in a function?
[英]Getting Name Error for a function I've defined earlier in the script
我正在建立一个Rectangle类,以查看两个矩形是否在拐角处接触。 这是最后一个练习由openbookproject为蟒蛇第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上方两行定义了它。 任何帮助将不胜感激!!!
如果方法same_coordinates
交集如上所示,则这是一个类方法,应该在对象上调用它。 如果将此方法移出类,则应该可以使用。
您可以尝试执行以下操作:
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进行调用。 我希望它能起作用!
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)
使用__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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.