考虑以下课程:
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 :(得分:3)
您需要将2个参数传递给WebPageTestProcessor
类url
和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个问题:
submitTest
方法。self.url
内部submitTest
方法,因为它是一个类属性。答案 1 :(得分:1)
self
也隐式传递给类的所有非静态方法。您需要像这样定义submitTest
:
def submitTest(self):
# ^^^^
response = json.load(urllib.urlopen(self.url))
# ^^^^^
return response["data"]["testId"]
您也会注意到我在self.
之前放置了url
。您需要这样做,因为url
是类的实例属性(只能通过self
访问)。