为什么我的方法不调用另一个(未定义变量)

2024-10-17 06:19:07 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我试了很多次,我不知道为什么当我想在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)

Tags: theinidgetdeforiginrouteclasses
2条回答

您已经在GetRide类中声明了haversine函数。在类内部声明它会使它成为类的实例方法。必须从类的实例调用实例方法。在

# Call it directly from a `GetRide` instance
my_get_ride = GetRide() # create an instance of the class
my_get_ride.haversine(lat1, lng1, lat2, lng2) # call it from the instance

# Or call it from within another method of `GetRide` from self
def get(self, ...):
    self.haversine(...)

假设您没有使用self参数声明haversine,那么这两个调用都会产生以下错误:

^{pr2}$

它说您给了它5,因为python将自动将实例作为lat1之前的第一个参数传入。真正发生的是:

haversine(my_get_ride, lat1, lng1, lat2, lng2)

您可以通过更新haversine方法来纠正这一问题,方法是像使用get方法一样使用第一个参数self,然后从必须从'self调用get方法的haversine。在

def haversine(self, lat1, lng1, lat2, lng2):
    # method body

def get(self, request, route_id):
    # first part of method body
        x = self.haversine(d_route.origin_lat,d_route.origin_lng, route.origin_lat, route.origin_lng )
    # second part of method body

或者,如果您不想在GetRide类中包含haversine,那么可以在同一个文件中的类之外,在{}类定义之前或之后声明它。在

# here it is defined outside of the class
def haversine(lat1, lng1, lat2, lng2):
    # method body

class GetRide(APIView):
    # other code
    def get(self, request, route_id):
        # method body

线路:

def haversine(lat1, lng1, lat2, lng2):

应该是:

^{pr2}$

和行:

x = haversine(d_route.origin_lat,d_route.origin_lng, route.origin_lat, route.origin_lng )

应该是:

x = self.haversine(d_route.origin_lat,d_route.origin_lng, route.origin_lat, route.origin_lng )

这是因为它们都位于Class中,而且所有函数都应该缩进到Class中。不确定它是否粘贴错误,或者它实际上看起来像.py文件中的那样。在

相关问题 更多 >