station
station

Reputation: 7145

How to pass self to a constructor

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

Answers (2)

Kobi K
Kobi K

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:

  1. Setting self to submitTest method.
  2. using the self.url inside submitTest method since it's a class attribute.
  3. fixing the instance creation of the class by passing 2 arguments as we declared.

Upvotes: 3

user2555451
user2555451

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

Related Questions