嗨,我试了很多次,我不知道为什么当我想在x上保存haversine()
时会出现以下错误:undefined Variable Haversine
。唯一有效的方法就是把haversine函数放在get funct里面
class GetRide(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def haversine(lat1, lng1, lat2, lng2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lng1, lat1, lng2, lat2 = map(radians, [lng1, lat1, lng2, lat2])
# haversine formula
dlng = lng2 - lng1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlng/2)**2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
def get(self, request, route_id):
d_route = Route.objects.get(id=route_id)
p_routes = Route.objects.all()
for route in p_routes:
x = haversine(d_route.origin_lat,d_route.origin_lng, route.origin_lat, route.origin_lng )
if ( x < 3):
new_route = 0
return Response(new_route,status=status.HTTP_200_OK)
您已经在
GetRide
类中声明了haversine
函数。在类内部声明它会使它成为类的实例方法。必须从类的实例调用实例方法。在假设您没有使用
^{pr2}$self
参数声明haversine
,那么这两个调用都会产生以下错误:它说您给了它5,因为python将自动将实例作为
lat1
之前的第一个参数传入。真正发生的是:您可以通过更新haversine方法来纠正这一问题,方法是像使用
get
方法一样使用第一个参数self
,然后从必须从'self调用get
方法的haversine
。在或者,如果您不想在}类定义之前或之后声明它。在
GetRide
类中包含haversine
,那么可以在同一个文件中的类之外,在{线路:
应该是:
^{pr2}$和行:
应该是:
这是因为它们都位于
Class
中,而且所有函数都应该缩进到Class
中。不确定它是否粘贴错误,或者它实际上看起来像.py文件中的那样。在相关问题 更多 >
编程相关推荐