簡體   English   中英

Python __add__方法無法正常工作,無法將參數傳遞回函數

[英]Python __add__ method not working properly with passing parameters back to the function

我有一段代碼使用Google Maps API來獲取給定位置之間的距離。 因此,例如Tour(“ New + York + NY”,“ Lansing + MI”,“ Sacramento + CA”)將計算NY和Lansing之間的位置,然后計算Lansing和Sacramento之間的位置並給出最終距離值。

我想使用add方法來指定另一個游覽,例如Tour(Oakland + CA)創建一個像Tour('New + York + NY','Lansing + MI','Sacramento + CA' ,奧克蘭+ CA),然后將其傳遞給Tour類,以計算具有新目的地的新距離。

我的代碼在下面,但是當我在add函數之后將值傳遞回時,我得到的距離為0。我知道Tour('New + York + NY','Lansing + MI','Sacramento + CA',奧克蘭+ CA)如果直接通過就可以單獨使用,但不能與add一起使用 我意識到我用strrepr可能做錯了什么,但我還不太了解。 感謝您的幫助,已經嘗試解決了幾個小時。

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('a') + Tour('b') -> Tour('a, b')

您希望Tour.__add__的行為如下:

Tour('a') + Tour('b') -> Tour('a', 'b')

您使用splat運算符允許Tour.__init__接受任意數量的參數,因此您必須在Tour.__add__執行相反的Tour.__add__ 這是有關此操作的示例:

def f(a, b, c):
    print(a, b, c)

f([1, 2, 3])   # TypeError: f() missing 2 required positional arguments: 'b' and 'c'

f(*[1, 2, 3])  # prints 1, 2, 3
f(1, 2, 3)     # prints 1, 2, 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM