2014-11-03 78 views
0

考慮下面的類:如何自我傳遞給構造

class WebPageTestProcessor: 

    def __init__(self,url,harUrl): 
     self.url = url 
     self.harUrl = harUrl 

    def submitTest(): 
     response = json.load(urllib.urlopen(url)) 
     return response["data"]["testId"] 

def main(): 
    wptProcessor = WebPageTestProcessor("http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321") 
    print wptProcessor.submitTest() 

if __name__ =='__main__':main() 

在運行時,它拋出一個錯誤說:

TypeError: __init__() takes exactly 3 arguments (2 given). 

我通過None作爲參數:

wptProcessor = WebPageTestProcessor(None,"http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321") 

然後它說:

TypeError: submitTest() takes no arguments (1 given) 

有誰知道如何將self傳遞給構造函數?

+0

你沒有通過'harUrl',你需要將自己添加到'submitTest(self)' – 2014-11-03 14:50:34

回答

3

你需要傳遞2個參數來urlWebPageTestProcessor類和harUrl

您只通過1這是

"http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321" 

自變量表示的對象本身的情況下,可以將其重命名爲任何你想要的名字。

的問題是您的訂單,請嘗試:

class WebPageTestProcessor(object): 
    def __init__(self,url,harUrl): 
     self.url = url 
     self.harUrl = harUrl 

    def submitTest(self): 
     response = json.load(urllib.urlopen(self.url)) 
     return response["data"]["testId"] 

def main(): 
    wptProcessor = WebPageTestProcessor("http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321", None) 
    print wptProcessor.submitTest() 

if __name__ == '__main__': 
    main() 

在我們有固定的3個問題,上面的代碼:

  1. 設置自我submitTest方法。
  2. 使用中的self.url方法,因爲它是一個類屬性。
  3. 通過傳遞2個參數來修復類的實例創建。
+0

感謝這個錯誤令人困惑,因爲它說3需要兩個給定的。我不小心以爲我已經通過了harUrl。 – station 2014-11-03 14:57:31

+0

@ user567797 NP答案解決了問題,您可以接受它作爲答案。 – 2014-11-04 09:11:28

1

self也隱式傳遞給類的所有非靜態方法。您需要定義submitTest像這樣:

def submitTest(self): 
#    ^^^^ 
    response = json.load(urllib.urlopen(self.url)) 
#          ^^^^^ 
    return response["data"]["testId"] 

你會發現太多,我放在self.url之前。您需要這樣做是因爲url是該類的實例屬性(它只能通過self訪問)。

+0

其中url是來自'json.load(urllib.urlopen(url))'嗎? – 2014-11-03 14:54:39

+0

@PadraicCunningham - 好。我會提到的。 – iCodez 2014-11-03 14:55:55

相關問題