调用GeoPoint类get_distance方法时提示缺少point参数的问题
错误原因及修复方案
核心错误原因
你代码里的geo = GeoPoint没有实例化类,只是把类本身赋值给了变量。当直接通过类调用实例方法get_distance时,Python不会自动传入self参数——此时你传的point3会被当作self,而原本需要的point参数就缺失了,所以报出"missing 1 required positional argument: 'point'"的错误。
具体修复步骤
1. 修复方法调用方式
实例方法必须通过类的实例调用,Python才会自动把实例作为self参数传入。比如你要计算point3和point1的距离,应该用point1.get_distance(point3),而不是用未实例化的类调用。
2. 修正get_distance的逻辑问题
你当前的get_distance方法里,先用实例的坐标赋值了lat1、lon1等变量,随后又用input重新覆盖了这些值,完全浪费了实例的坐标数据。应该删除多余的input代码,直接使用实例存储的经纬度计算距离,并且返回计算结果(方便后续比较)。修改后的方法如下:
def get_distance(self, point): lat1 = radians(self.lat) lon1 = radians(self.lon) lat2 = radians(point.lat) lon2 = radians(point.lon) # 计算两点间球面距离 dist = 6371.01 * acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon1 - lon2)) return dist
3. 修复其他语法/逻辑问题
dist = ()是不可变元组,无法进行dist[1]这类赋值操作,改成字典或列表(比如dist = {})存储不同点的距离。point3 = GeoPoint(latlon, Loc)会把元组latlon直接传给lat参数,导致lon用默认值0,正确写法是point3 = GeoPoint(*latlon, Loc),用拆包方式传递经纬度。- 调用
point2.point赋值时,建议加上括号明确元组:point2.point = (23.4567, -213.456)。
修改后的完整调用脚本
from GeoPoint import GeoPoint def doanother(): '''Asks user if they want to do another and returns True or False''' usr_response = input("Do another (y/n)? ") another = usr_response.strip()[0].lower() == 'y' return another while True: try: dist = {} point1 = GeoPoint(12.3456, -123.4567, 'Loc1') point2 = GeoPoint() point2.point = (23.4567, -213.456) point2.description = 'Loc2' # 获取用户坐标 choice = input('Enter the lat and lon of your location (format: lat, lon): ') latlon = tuple(map(float, choice.split(', '))) print("Your coordinates:", latlon) Loc = input('Enter your location name: ') # 初始化用户位置实例 point3 = GeoPoint(*latlon, Loc) # 计算到两个预设点的距离 dist[point1.description] = point1.get_distance(point3) dist[point2.description] = point2.get_distance(point3) # 找出最短距离及对应地点 shortest_dist = min(dist.values()) closest_loc = [loc for loc, distance in dist.items() if distance == shortest_dist][0] print(f'The shortest distance is {shortest_dist:.2f}km, to {closest_loc}') except Exception as e: print(f'Error: {e}') if not doanother(): break
内容的提问来源于stack exchange,提问作者Scott Bing
相关产品推荐
相关产品推荐

