我有一段代码,它使用googlemapsapi获取给定位置之间的距离。因此,例如Tour('New+York+NY'、'Lansing+MI'、'Sacramento+CA')将计算纽约和兰辛之间的位置,然后Lansing和Sacramento给出最终的距离值。你知道吗
我想使用add方法来指定另一个旅游,例如tour(奥克兰+加州)来创建一个新的路线,比如tour('new+York+NY'、'Lansing+MI'、'Sacramento+CA'、Oakland+CA),然后将其传递给班级旅游,以计算与新目的地的新距离。你知道吗
下面是我的代码,但是当我在add函数后返回值时,我得到的距离是0。我知道Tour(“纽约+纽约+纽约”,“兰辛+密苏里州”,“萨克拉门托+加利福尼亚州”,奥克兰+加利福尼亚州)如果直接过世就可以自己工作,但无法让它与add一起工作;我意识到我可能对str或repr做了一些错事,我还不太了解这些。任何帮助都将不胜感激,我们已经努力解决了几个小时了。你知道吗
import requests
import json
class Tour:
def __init__ (self, *args):
self.args = args
def __str__ (self):
# returns New+York+NY;Lansing+MI;Los+Angeles+CA
return ' '.join(self.args)
def __repr__ (self):
# returns New+York+NY;Lansing+MI;Los+Angeles+CA
return ' '.join(self.args)
def distance (self, mode = 'driving'):
self.mode = mode
meters_list = []
# counts through the amount of assigned arguments, 'Lansing+MI', 'Los+Angeles+CA' will give 2
for i in range(len(self.args)-1):
#print (self.args[i])
url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=%s&destinations=%s&mode=%s&sensor=false' % (self.args[i], self.args[i+1], self.mode)
response = requests.get(url)
# converts json data into a python dictionary
jsonAsPython = json.loads(response.text)
# gets the dictionary value for the metres amount by using the relevent keys
meters = int(jsonAsPython['rows'][0]['elements'][0]['distance']['value'])
#print (meters)
meters_list.append(meters)
return (sum(meters_list))
def __add__ (self, other):
new_route = str(','.join(self.args + other.args))
return Tour(new_route)
a = Tour('New+York+NY', 'Lansing+MI','Sacramento+CA')
b = Tour('Oakland+CA')
print (a)
print (b)
print (a.distance())
c = a + b
print(c)
print (c.distance())
以防万一,这里还有到原始项目的链接:http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/08_ClassDesign/GoogleMap/Project11.pdf
当前的
Tour.__add__
函数执行如下操作:您希望
Tour.__add__
的行为如下:您使用splat运算符来允许
Tour.__init__
接受任意数量的参数,因此您必须在Tour.__add__
中执行相反的操作。下面是一个如何做到这一点的示例:相关问题 更多 >
编程相关推荐