'global name <function in same namespace> is not defined' - 为什么会这样?



我正在尝试在 Pygame 中进行一些多边形旋转,所以我正在做一些点积并获取弧度并将 acos 应用于这些弧度。根据这个链接,我应该使用钳位函数将点积保持在 -1 和 1 之间。但是,我收到以下错误:

d_p = (clamp(self.dot_product(other), -1.0, 1.0))
NameError: global name 'clamp' is not defined

它们似乎位于同一命名空间中 - 这与它们在代码中显示的完全相同。我尝试在 clamp() 上使用@staticmethod,但它保持不变。唯一有效的是使其成为实例方法(签名clamp(self, x, a, b)但是当 clamp 不需要了解特定实例时,这似乎是一个糟糕的解决方案。解决这个问题的正确方法是什么,我错过了什么概念?

class v2:
#...
def clamp(x, a, b):
return min(max(x, a), b)
def radians_between(self, other):
d_p = (clamp(self.dot_product(other), -1.0, 1.0))
cos_of_angle = d_p/(self.get_magnitude()*other.get_magnitude())
return math.acos(cos_of_angle)

为了解决此问题,在定义它的类中使用它时,必须使用self.clamp()。否则,如果从类外部调用v2.clamp(),则必须使用 。

它之所以说global name 'clamp' is not defined,是因为它认为"clamp"应该是全局范围内的变量、函数或类,例如:

class clamp(object):
pass

或:

clamp="I am a variable!"

或最后:

def clamp():
print "I am clamp in a function!"

最新更新