Reputation: 7145
Consider the following class:
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()
Upon running, it throws an error saying:
TypeError: __init__() takes exactly 3 arguments (2 given).
I passed None
as the argument:
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")
and then it says:
TypeError: submitTest() takes no arguments (1 given)
Does anyone know how to pass self
to the constructor?
Upvotes: 0
Views: 569
Reputation: 7931
You need to pass 2 arguments toWebPageTestProcessor
class url
and harUrl
You are passing only 1 which is
"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"
The self variable represents the instance of the object itself, you can rename it to any name you want.
The problem is your order, try:
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()
At the above code we have fixed 3 issues:
submitTest
method.self.url
inside submitTest
method since it's a class attribute.Upvotes: 3
Reputation:
self
is also passed implicitly to all non-static methods of a class. You need to define submitTest
like so:
def submitTest(self):
# ^^^^
response = json.load(urllib.urlopen(self.url))
# ^^^^^
return response["data"]["testId"]
You'll notice too that I placed self.
before url
. You need this because url
is an instance attribute of the class (it is only accessible through self
).
Upvotes: 1