2014-11-03 86 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

相关问题